Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Template is_polymorphic ใน C++

ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_polymorphic ใน C++ STL

is_polymorphic เป็น template ใน header <type_traits> ใช้ตรวจสอบว่าคลาสเป็น polymorphic class หรือไม่ คืนค่า true หรือ false

Polymorphic Class คืออะไร?

คลาสที่ประกาศ virtual function จาก abstract class ที่ประกาศ virtual function ไว้ คลาสนี้มีการประกาศ virtual function ที่ประกาศในคลาสอื่น

ไวยากรณ์

template <class T> is_polymorphic;

พารามิเตอร์

Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น polymorphic class หรือไม่

ค่าที่คืน

คืนค่า Boolean: true หากเป็น polymorphic class, false หากไม่ใช่

ตัวอย่าง

Input: class B { virtual void fn(){} }; class C : B {}; is_polymorphic<B>::value; Output: true
Input: class A {}; is_polymorphic<A>::value; Output: false

ตัวอย่างโค้ด 1

#include <iostream>
#include <type_traits>
using namespace std;

struct TP { virtual void display(); };
struct TP_2 : TP { };
class TP_3 { virtual void display() = 0; };
struct TP_4 : TP_3 { };

int main() {
    cout << boolalpha;
    cout << "Checking for is_polymorphic: ";
    cout << "\n structure TP with one virtual function : " << is_polymorphic<TP>::value;
    cout << "\n structure TP_2 inherited from TP: " << is_polymorphic<TP_2>::value;
    cout << "\n class TP_3 with one virtual function: " << is_polymorphic<TP_3>::value;
    cout << "\n class TP_4 inherited from TP_3: " << is_polymorphic<TP_4>::value;
    return 0;
}

เอาต์พุต

Checking for is_polymorphic:
structure TP with one virtual function : true
structure TP_2 inherited from TP: true
class TP_3 with one virtual function: true
class TP_4 inherited from TP_3: true

ตัวอย่างโค้ด 2

#include <iostream>
#include <type_traits>
using namespace std;

struct TP { int var; };
struct TP_2 { virtual void display(); };
class TP_3 : TP_2 { };

int main() {
    cout << boolalpha;
    cout << "Checking for is_polymorphic: ";
    cout << "\n structure TP with one variable : " << is_polymorphic<TP>::value;
    cout << "\n structure TP_2 with one virtual function : " << is_polymorphic<TP_2>::value;
    cout << "\n class TP_3 inherited from structure TP_2: " << is_polymorphic<TP_3>::value;
    return 0;
}

เอาต์พุต

Checking for is_polymorphic:
structure TP with one variable : false
structure TP_2 with one virtual function : true
class TP_3 inherited from structure TP_2 : true