在本文中,我们将讨论C ++ STL中std::is_polymorphic模板的工作,语法和示例。
is_polymorphic是C ++中<type_traits>头文件下的模板。该模板用于检查该类是否为多态类,并相应地返回结果true或false。
从声明虚拟函数的抽象类中声明虚拟函数的类。该类具有在其他类中声明的虚函数的声明。
template <class T> is_polymorphic;
模板只能具有类型T的参数,并检查给定类型是否为多态类。
它返回一个布尔值,如果给定类型是多态类,则返回true,如果给定类型不是多态类,则返回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#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
#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