我有一个继承自模板定义类型的类型。模板定义的类型保证具有给定的基类。我想做的是能够在容器中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]);
答案 0 :(得分:1)
正如Creris&#39;所建议的那样。在注释中,您需要一个非模板化的基类,这对于您的所有Derived<>
模板类都是通用的。此外,Base
本身的继承应该是虚拟的,因此在Base
实例化时只有一个Derived<>
实例。
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));