【发布时间】:2019-07-06 09:02:15
【问题描述】:
在寻找将 CRTP 对象存储在容器中的方法时,我发现了以下问题:
A polymorphic collection of Curiously Recurring Template Pattern (CRTP) in C++?
我尝试了标记的解决方案
https://stackoverflow.com/a/24795227/5475431
但编译器会抱怨如下错误:
no known conversion for argument 1 from ‘std::shared_ptr<DerivedA>’ to ‘const std::shared_ptr<BaseInterface>&’
这是我的尝试:
#include <vector>
#include <memory>
struct BaseInterface {
virtual ~BaseInterface() {}
virtual double interface() = 0;
};
template <typename Derived>
class Base : BaseInterface {
public:
double interface(){
return 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;}
};
int main() {
std::vector<std::shared_ptr<BaseInterface>> ar;
ar.emplace_back(std::make_shared<DerivedA>());
return 0;
}
您知道如何修复编译器错误,或者如何更好地解决问题吗? 提前致谢
【问题讨论】:
-
为什么需要混合使用 CRTP 和运行时多态性?
-
class Base : BaseInterface使用私有继承,因此从Base派生的类的指针不能转换为BaseInterface*。 -
顺便说一句,当您粘贴错误消息时,指出它发生在代码中的位置真的很有用。编译器会显示你,所以你应该显示给我们(反正行号容易断,显示位置更好)。
-
@FrançoisAndrieux 首先正确回答了上述问题。你应该发布一个答案:)
-
@FrançoisAndrieux 非常感谢您的评论;问题战争私有派生
标签: c++ c++11 templates vector crtp