【发布时间】:2022-01-01 22:45:36
【问题描述】:
我有一个类Base,其中有两个类,DerivedA 和DerivedB,定义如下。
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:
std::vector<std::shared_ptr<Derived>>
这显然是不可能的,因为我现在已将 Derived 类设为模板类。
有什么方法可以创建/维护对象的多态集合?
编辑:不幸的是,一个简单的模板化结构不起作用,因为函数implementation 在我的实际程序中是模板化的——所以implementation 必须是一个模板化的纯虚函数,这是不可能的。请原谅我缺乏解释。
【问题讨论】:
-
-1 显示的代码在语法上无效(例如
Class) -
和
Derived不是您的伪代码中的类型 -
抱歉,修复了我的示例中的一连串拼写错误。当前(更新)的帖子格式正确。我没有模板元编程可以做吗?
-
@quantdev 我认为他的意思是
Base。用户:你为什么不能放弃 CRTP 并使用virtual函数?请不要回复purrformance。 -
@Galik 你不能有一个模板化的(纯)虚函数。
标签: c++ inheritance c++11 polymorphism crtp