简体   繁体   English

比较C ++中的类类型

[英]Compare class types in C++

I need to compare two classes, more exactly their types. 我需要比较两个类,更确切地说是它们的类型。 I wrote the following code: 我写了以下代码:

class Base {};
class Derived : public Base {};

class Engine
{
public:
    template <class T>
    T addComponent();
};

template <class T>
T Engine::addComponent()
{
    Base* isRight = dynamic_cast<Base*>(T);
    if (!isRight)
        throw("Error!");

    return T();
}

And then I call it 然后我称之为

int main()
{
    Engine engine = Engine();
    Derived derived = engine.addComponent<Derived>();
}

Well, I know, dynamic_cast works only on instances of the class. 好吧,我知道, dynamic_cast仅适用于该类的实例。 I hope you know a solution. 希望您知道解决方案。

I believe you're looking for std::is_base_of . 我相信您正在寻找std :: is_base_of And since it's a static thing, you can do this check entirely at compile time: 而且由于这是静态的,因此您可以在编译时完全执行此检查:

template <class T>
T Engine::addComponent()
{
    static_assert(std::is_base_of<Base, T>::value, "T doesn't derive from Base!");

    return T();
}

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

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