C++ vector of CRTP shared pointers

拜拜、爱过 提交于 2020-05-16 06:01:05

问题


In my search for a way to store CRTP objects in a container, I found the following question:

A polymorphic collection of Curiously Recurring Template Pattern (CRTP) in C++?

I tryied the marked solution

https://stackoverflow.com/a/24795227/5475431

but the compiler is complainings erros like:

no known conversion for argument 1 from ‘std::shared_ptr<DerivedA>’ to ‘const std::shared_ptr<BaseInterface>&’

here is my try:

#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;
}

do you have any idea how to fix the compiler error, or how to solve the problem better? Thanks in advance


回答1:


Base should be an public inheritance of BaseInterface(and you also forgot return). Then ar.emplace_back(std::make_shared<DerivedA>()); well works:

DEMO

template <typename Derived>
class Base : public BaseInterface {
public:
    double interface(){
        return static_cast<Derived*>(this)->implementation();
    }
};



回答2:


You're missing a return statement and Base should inherit from BaseInterfacepublically.

template <typename Derived>
struct Base : BaseInterface
{
    double interface() {
        return static_cast<Derived*>(this)->implementation();
    }
};

Live demo

But beware https://stackoverflow.com/a/24795059/5470596 <-- the answer the other OP should have accepted.



来源:https://stackoverflow.com/questions/54654770/c-vector-of-crtp-shared-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!