ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_empty ใน C++ STL
is_empty เป็น template ใน header <type_traits> ใช้ตรวจสอบว่าคลาส T เป็น empty class หรือไม่
Empty Class คืออะไร?
คลาสที่ไม่มีข้อมูลเก็บอยู่ในคลาส Empty class ต้องเป็นไปตามเงื่อนไข:
- ไม่มี non-static members ยกเว้น bit fields ที่มีความยาว 0
- ไม่มี virtual base class หรือ virtual functions
- ไม่มี base class
ไวยากรณ์
template <class T> is_empty;
พารามิเตอร์
Template รับพารามิเตอร์คลาส T เพียงอย่างเดียว ตรวจสอบว่าเป็น empty class หรือไม่
ค่าที่คืน
คืนค่า Boolean: true หากเป็น empty class, false หากไม่ใช่
ตัวอย่าง
Input: class A{}; is_empty<A>::value; Output: true
Input: class B{ void fun() {} }; is_empty<B>::value; Output: true
ตัวอย่างโค้ด 1
#include <iostream>
#include <type_traits>
using namespace std;
class TP_1 { };
class TP_2 { int var; };
class TP_3 { static int var; };
class TP_4 { ~TP_4(); };
int main() {
cout << boolalpha;
cout << "checking for is_empty template for a class with no variable: " << is_empty<TP_1>::value;
cout << "\nchecking for is_empty template for a class with one variable: " << is_empty<TP_2>::value;
cout << "\nchecking for is_empty template for a class with one static variable: " << is_empty<TP_3>::value;
cout << "\nchecking for is_empty template for a class with constructor: " << is_empty<TP_4>::value;
return 0;
}
เอาต์พุต
checking for is_empty template for a class with no variable: true checking for is_empty template for a class with one variable: false checking for is_empty template for a class with one static variable: true checking for is_empty template for a class with constructor: true
ตัวอย่างโค้ด 2 (Struct)
#include <iostream>
#include <type_traits>
using namespace std;
struct TP_1 { };
struct TP_2 { int var; };
struct TP_3 { static int var; };
struct TP_4 { ~TP_4(); };
int main() {
cout << boolalpha;
cout << "checking for is_empty template for a structure with no variable: " << is_empty<TP_1>::value;
cout << "\nchecking for is_empty template for a structure with one variable: " << is_empty<TP_2>::value;
cout << "\nchecking for is_empty template for a structure with one static variable: " << is_empty<TP_3>::value;
cout << "\nchecking for is_empty template for a structure with constructor: " << is_empty<TP_4>::value;
return 0;
}
เอาต์พุต
checking for is_empty template for a structure with no variable: true checking for is_empty template for a structure with one variable: false checking for is_empty template for a structure with one static variable: true checking for is_empty template for a structure with constructor: true