ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_void ใน C++ STL
is_void เป็น template ใน header <type_traits> ใช้ตรวจสอบว่าชนิด T เป็น void type หรือไม่
Void Type ใน C++ คืออะไร?
Void หมายถึง "ว่างเปล่า" หรือ "ไม่มีอะไร" เมื่อประกาศฟังก์ชันเป็น void หมายถึงฟังก์ชันนั้นไม่คืนค่า
Void pointers ถูกใช้เมื่อชนิดข้อมูลไม่ได้ระบุชัดเจน ต้องอ้างอิงตัวแปรชนิดอื่นก่อน dereference ชี้ไปยังออบเจกต์ได้ทุกชนิด จึงมีประโยชน์มาก
ไวยากรณ์
template <class T> is_void;
พารามิเตอร์
Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น void type หรือไม่
ค่าที่คืน
คืนค่า Boolean: true หากเป็น void type, false หากไม่ใช่
ตัวอย่าง
Input: is_void<void>::value; Output: true Input: is_void<int>::value; Output: false
ตัวอย่างโค้ด 1
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
cout << boolalpha;
cout << "checking for is_void:";
cout << "\nvoid:" << is_void<void>::value;
cout << "\nconst void:" << is_void<const void>::value;
cout << "\nint:" << is_void<int>::value;
cout << "\nchar:" << is_void<char>::value;
return 0;
}
เอาต์พุต
checking for is_void: Void: true Const void: true Int: false Char: false
ตัวอย่างโค้ด 2
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
cout << boolalpha;
cout << "checking for is_void:";
cout << "\nDouble:" << is_void<double>::value;
cout << "\nFloat:" << is_void<float>::value;
cout << "\nvolatile void:" << is_void<volatile void>::value;
cout << "\nconst volatile void:" << is_void<const volatile void>::value;
return 0;
}
เอาต์พุต
checking for is_void: Double: false Float: false Volatile void: true Const volatile void: true