ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_pod ใน C++ STL
is_pod เป็น template ใน header <type_traits> ใช้ตรวจสอบว่าชนิด T เป็น POD (Plain Old Data) type หรือไม่
POD (Plain Old Data) คืออะไร?
POD types คือชนิดที่มีอยู่ใน C แบบเก่า รวมถึง scalar types POD class type คือคลาสที่เป็นทั้ง trivial (initialize แบบ static ได้) และ standard layout (โครงสร้างข้อมูลแบบง่ายเหมือน struct/union)
ไวยากรณ์
template <class T> is_pod;
พารามิเตอร์
Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น POD type หรือไม่
ค่าที่คืน
คืนค่า Boolean: true หากเป็น POD, false หากไม่ใช่
ตัวอย่าง
Input: class final_abc{ final_abc(); }; is_pod<final_abc>::value; Output: false
Input: is_pod<int>::value; Output: true
ตัวอย่างโค้ด 1 (Struct)
#include <iostream>
#include <type_traits>
using namespace std;
struct TP_1 { int var_1; };
struct TP_2 { int var_2; private: int var_3; };
struct TP_3 { virtual void dummy(); };
int main() {
cout << boolalpha;
cout << "checking for is_pod:";
cout << "\nTP_1: " << is_pod<TP_1>::value;
cout << "\nTP_2: " << is_pod<TP_2>::value;
cout << "\nTP_3: " << is_pod<TP_3>::value;
return 0;
}
เอาต์พุต
checking for is_pod: TP_1: true TP_2: false TP_3: false
ตัวอย่างโค้ด 2 (Class)
#include <iostream>
#include <type_traits>
using namespace std;
class TP_1 { int var_1; };
class TP_2 { int var_2; private: int var_3; };
class TP_3 { virtual void dummy(); };
int main() {
cout << boolalpha;
cout << "checking for is_pod:";
cout << "\nTP_1: " << is_pod<TP_1>::value;
cout << "\nTP_2: " << is_pod<TP_2>::value;
cout << "\nTP_3: " << is_pod<TP_3>::value;
return 0;
}
เอาต์พุต
checking for is_pod: TP_1: true TP_2: true TP_3: false
หมายเหตุ
- Struct และ Class ที่มีเฉพาะ non-static data members โดยไม่มี access specifier ต่างกัน จะเป็น POD
- มี private member ทำให้ struct ไม่เป็น POD (แต่ class ยังเป็นได้)
- มี virtual function ทำให้ไม่เป็น POD
- C++20 deprecated is_pod ใช้แทนด้วย is_trivial และ is_standard_layout