ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_abstract ใน C++ STL
is_abstract template ช่วยตรวจสอบว่าคลาสเป็น abstract class หรือไม่
Abstract Class คืออะไร?
Abstract class คือคลาสที่มี pure virtual function อย่างน้อย 1 ตัว ใช้เมื่อเรารู้ว่าต้องมีฟังก์ชันแบบนี้แต่ยังไม่รู้การทำงาน ใช้ pure virtual function ที่ประกาศอย่างเดียวไม่มี implementation
is_abstract() สืบทอดจาก integral_constant คืนค่า true_type หรือ false_type ขึ้นอยู่กับว่าคลาส T เป็น polymorphic class type หรือไม่
ไวยากรณ์
template <class T> struct is_abstract;
พารามิเตอร์
Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น abstract class หรือไม่
ค่าที่คืน
คืนค่า bool: true หากเป็น abstract class, false หากไม่ใช่
ตัวอย่างโค้ด 1
#include <iostream>
#include <type_traits>
using namespace std;
struct TP_1 { int var; };
struct TP_2 { virtual void dummy() = 0; };
class TP_3 : TP_2 { };
int main() {
cout << boolalpha;
cout << "checking for is_abstract: ";
cout << "\nstructure TP_1 with one variable :" << is_abstract<TP_1>::value;
cout << "\nstructure TP_2 with one virtual variable : " << is_abstract<TP_2>::value;
cout << "\nclass TP_3 which is derived from TP_2 structure : " << is_abstract<TP_3>::value;
return 0;
}
เอาต์พุต
checking for is_abstract: structure TP_1 with one variable : false structure TP_2 with one virtual variable : true class TP_3 which is derived from TP_2 structure : true
ตัวอย่างโค้ด 2
#include <iostream>
#include <type_traits>
using namespace std;
struct TP_1 { virtual void dummy() = 0; };
class TP_2 { virtual void dummy() = 0; };
struct TP_3 : TP_2 { };
int main() {
cout << boolalpha;
cout << "checking for is_abstract: ";
cout << "\nstructure TP_1 with one virtual function :" << is_abstract<TP_1>::value;
cout << "\nclass TP_2 with one virtual function : " << is_abstract<TP_2>::value;
cout << "\nstructure TP_3 which is derived from TP_2 class : " << is_abstract<TP_3>::value;
return 0;
}
เอาต์พุต
checking for is_abstract: structure TP_1 with one virtual function : true class TP_2 with one virtual function : true structure TP_3 which is derived from TP_2 class : true