C++ 中的 is_polymorphic 模板


在本文中,我们将讨论 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

更新于: 23-Mar-2020

47 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.