【发布时间】:2016-08-07 03:35:18
【问题描述】:
我有这样的类层次结构:
template <class Type>
class CrtpBase
{
protected:
Type& real_this()
{
return static_cast<Type&>(*this);
}
};
template <class ChildType>
class Base : CrtpBase<ChildType>
{
public:
void foo()
{
this->real_this().boo();
}
};
class Derived1 : public Base<Derived1>
{
public:
void boo { ... }
};
class Derived2 : public Base<Derived2>
{
public:
void boo { ... }
};
问题是,我想以这种方式使用我的课程:
std::vector<Base*> base_vec;
base_vec.push_bach(new Derived1());
base_vec.push_bach(new Derived2());
.........
base_vec[0]->foo();
但这是不可能的,因为所有派生类的基类都是不同的(实际上 Base 根本不是类型,它是模板)。那么,有没有办法将 crtp 与多个派生类一起使用,以及多态性?
【问题讨论】:
标签: c++ templates inheritance virtual-functions crtp