ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_pointer ใน C++ STL
is_pointer เป็น template ใน header <type_traits> ใช้ตรวจสอบว่าชนิด T เป็น pointer type หรือไม่
Pointer คืออะไร?
Pointers เป็น non-static types ที่เก็บที่อยู่ของชนิดอื่น หรือชี้ไปยังตำแหน่งหน่วยความจำ ใช้ asterisk * ประกาศ และ dereference ก็ใช้ * เช่นกัน
สามารถ initialize เป็น null ได้ และเปลี่ยนชนิดได้ตามต้องการ
ไวยากรณ์
template <class T> is_pointer;
พารามิเตอร์
Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น pointer หรือไม่
ค่าที่คืน
คืนค่า Boolean: true หากเป็น pointer variable, false หากไม่ใช่
ตัวอย่าง
Input: is_pointer<int>::value; Output: false Input: is_pointer<int*>::value; Output: true
ตัวอย่างโค้ด 1
#include <iostream>
#include <type_traits>
using namespace std;
class TP { };
int main() {
cout << boolalpha;
cout << "checking for is_pointer:";
cout << "\nTP: " << is_pointer<TP>::value;
cout << "\nTP*: " << is_pointer<TP*>::value;
cout << "\nTP&: " << is_pointer<TP&>::value;
cout << "\nNull Pointer: " << is_pointer<nullptr_t>::value;
return 0;
}
เอาต์พุต
checking for is_pointer: TP: false TP*: true TP&: false Null Pointer: false
ตัวอย่างโค้ด 2
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
cout << boolalpha;
cout << "checking for is_pointer:";
cout << "\nint: " << is_pointer<int>::value;
cout << "\nint*: " << is_pointer<int*>::value;
cout << "\nint **: " << is_pointer<int**>::value;
cout << "\nint ***: " << is_pointer<int***>::value;
return 0;
}
เอาต์พุต
checking for is_pointer: int: false int*: true int **: true int ***: true
หมายเหตุ
nullptr_tไม่ใช่ pointer type (คืน false)- Pointer to pointer (int**, int***) ก็ยังเป็น pointer type (คืน true)
- Reference types (int&) ไม่ใช่ pointer (คืน false)