简体   繁体   中英

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. I hope you know a solution.

I believe you're looking for 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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