CRTP共享指针的C ++向量 [英] C++ vector of CRTP shared pointers

查看:103
本文介绍了CRTP共享指针的C ++向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在寻找一种将CRTP对象存储在容器中的方法时,我发现了以下问题:

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

C ++中的CRP的多态集合?

我尝试了标记的解决方案

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>&’

这是我的尝试:

#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

推荐答案

Base 应该是公共的 BaseInterface 的继承(并且您也忘记了 return )。
然后 ar.emplace_back(std :: make_shared< DerivedA>()); 运行良好:

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

演示

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

这篇关于CRTP共享指针的C ++向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆