简体   繁体   English

如果类型是多态的,如何在编译时检查

[英]How to check at compile time if type is polymorhic

I have template function. 我有模板功能。 In the template function I am using dynamic_cast on the template argument. 在模板函数中,我在模板参数上使用dynamic_cast。 But since you can't use dynamic_cast on non polymorphic type, I want to check if type is polymorphic ( has at least one virtual function ) at compile time, and if type is not polymorphic I will skip using dynamic_cast. 但由于你不能在非多态类型上使用dynamic_cast,我想在编译时检查类型是否是多态的(至少有一个虚函数),如果type不是多态的,我将跳过使用dynamic_cast。 Is this possible ? 这可能吗 ?

You can use std::is_polymorphic : 你可以使用std::is_polymorphic

struct Foo {};

std::cout << std::is_polymorphic<Foo>::value << std::endl;

You can use this in combination with std::enable_if to use different code depending on its value. 您可以将它与std::enable_if结合使用,以根据其值使用不同的代码。

Another way compared to @juanchopanza 与@juanchopanza相比的另一种方式

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM