如何在编译时检查类型是否为polymorhic

How to check at compile time if type is polymorhic

本文关键字:类型 是否 polymorhic 检查 编译      更新时间:2023-10-16

我有模板函数。在template函数中,我对template参数使用dynamic_cast。但是,由于不能在非多态类型上使用dynamic_cast,我想在编译时检查类型是否是多态的(至少有一个虚拟函数),如果类型不是多态的,我将跳过使用dynamic_cast。这可能吗?

您可以使用std::is_polymorphic:

struct Foo {};
std::cout << std::is_polymorphic<Foo>::value << std::endl;

您可以将其与std::enable_if结合使用,根据其值使用不同的代码。

与@juancopanza 相比的另一种方式

template<class T>
struct IsPolymorphic
{
    struct Derived : T {
        virtual ~Derived();
    };
    enum  { value = sizeof(Derived)==sizeof(T) };
};
class PolyBase {
public:   
    virtual ~PolyBase(){}
};
class NPolyBase {
public:
    ~NPolyBase(){}
};
void ff()
{
    std::cout << IsPolymorphic<PolyBase >::value << std::endl;
    std::cout << IsPolymorphic<NPolyBase>::value << std::endl;
}