dynamic_cast 具有"Known"继承的模板类
dynamic_cast Template class with "Known" Inheritance
我有一个从模板定义的类型继承而来的类型。模板定义的类型保证具有给定的基类。我想做的是能够在容器中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在评论中所建议的那样,当T
不是Base
时,您需要一个对所有Derived<T>
模板类都通用的基类。此外,对Base
本身的继承应该是虚拟的,因此在实例化Derived<>
时只有一个Base
实例。
struct Base { virtual ~Base () = default; };
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));
但是,您可以使用模板专门化,这样公共基类实际上就是Derived<Base>
本身。
struct Base { virtual ~Base () = default };
struct Base2 : virtual Base {};
template <typename = Base> struct Derived;
template <>
struct Derived<Base> : virtual Base {};
template <typename BASE>
struct Derived : Derived<Base>, BASE {};
Base *b = new Derived<Base2>;
assert(dynamic_cast<Derived<> *>(b));
在线试用!
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- dynamic_cast 具有"Known"继承的模板类