dynamic_cast 具有 "Known" 继承的模板 class

dynamic_cast Template class with "Known" Inheritance

我有一个继承自模板定义类型的类型。模板定义的类型保证具有给定的基数 class。我想要做的是能够 dynamic_cast 或以其他方式在容器中找到与我的派生类型匹配的类型,而不管模板参数如何。

// A bunch of classes exist which inherit from Base already.
class Base{};
class Base2 : public Base {};
class BaseN : public Base {};

// Some new classes can inherit from any Base-derived class,
// but also have special attributes (i.e. function "f").
template<typename T = Base>
class Derived : public T
{
    static_assert(std::is_base_of<Base, T>::value, 
        "Class must inherit from a type derived from Base.")

    public:
        void f();
};

//
// Now process a collection of Base pointers.  
//

std::vector<Base*> objects;

// The vector may contain classes that are not "Derived".
// I only care about the ones that are.
// I want the cast here to return non-null for Derived<Base>, 
// Derived<Base2>, Derived<BaseN>, but null for Base, Base2, etc.

// This will be Null, Good.
objects.push_back(new Base)
auto dcast0 = dynamic_cast<Derived<Base>*>(objects[0]);

// This will be Non Null, Good.
objects.push_back(new Derived<Base>);
auto dcast1 = dynamic_cast<Derived<Base>*>(objects[1]);

// This will be Null, BAD! HELP!
objects.push_back(new Derived<Base2>);
auto dcast2 = dynamic_cast<Derived<Base>*>(objects[2]);

正如 Creris 在评论中所建议的那样,您需要一个非模板化的基础 class,这是所有 Derived<> 模板 class 所共有的。另外,对Base本身的继承应该是虚的,这样实例化Derived<>时只有一个Base实例。

struct Base { virtual ~Base () {} };
struct Base2 : virtual Base {};

struct DerivedBase : virtual Base {};

template <typename BASE = Base>
struct Derived : DerivedBase, BASE {};

    Base *b = new Derived<Base2>;
    assert(dynamic_cast<DerivedBase *>(b));