问题描述
我有一个类Base
,从中有两个类,如下所述,分别为DerivedA
和DerivedB
.
I've got a class Base
from which I have two classes, DerivedA
and DerivedB
as defined below.
template <typename Derived>
class Base{
public:
double interface(){
static_cast<Derived*>(this)->implementation();
}
};
class DerivedA : public Base<DerivedA>{
public:
double implementation(){ return 2.0;}
};
class DerivedB : public Base<DerivedB>{
public:
double implementation(){ return 1.0;}
};
简而言之,我正在尝试执行以下操作来维护对象的集合,其中有些是DerivedA
,有些是DerivedB
:
In short, I'm trying to do the following to maintain a collection of objects, some of which are DerivedA
and some of which are DerivedB
:
std::vector<std::shared_ptr<Derived>>
这显然是不可能的,因为我现在已经将类Derived
设置为模板化类.
Which is obviously impossible beacuse I've now made the class Derived
a templated class.
有什么方法可以创建/维护对象的多态集合?
Is there any way I can create / maintain a polymorphic collection of objects?
不幸的是,由于在我的实际程序中将函数implementation
进行了模板化,所以简单的模板化结构不起作用-因此,implementation
将必须是模板化的纯虚函数,而不能是.请原谅我缺乏解释.
Unfortunately, a simple templated structure does not work as the function implementation
is templated in my actual program -- so then implementation
would have to be a templated pure virtual function, which cannot be. Pardon my lack of explanation.
推荐答案
Alf的建议已达到目标.很容易将其适应您的其他要求.使用纯虚方法定义接口:
Alf's suggestion is on target. It is easy to adapt it to your additional requirement. Define an interface with a pure virtual method:
struct BaseInterface {
virtual ~BaseInterface() {}
virtual double interface() = 0;
};
现在,您的模板基类可以从该接口派生:
Now, your template base class can derive from the interface:
template <typename Derived>
class Base : BaseInterface {
public:
double interface(){
static_cast<Derived*>(this)->implementation();
}
};
现在,您可以创建一个指向接口的指针向量:
Now, you can create a vector of pointers to the interface:
std::vector<std::shared_ptr<BaseInterface>>
这篇关于C ++中的好奇重复模板模式(CRTP)的多态集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!