【问题标题】:C++ vector of CRTP shared pointersCRTP 共享指针的 C++ 向量
【发布时间】: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


【解决方案1】:

Base 应该是BaseInterface 的公共继承(你也忘记了return)。 然后ar.emplace_back(std::make_shared&lt;DerivedA&gt;()); 很好用:

DEMO

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

【讨论】:

    【解决方案2】:

    您缺少返回语句并且Base 应该从BaseInterfacepublically 继承。

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

    Live demo

    但要小心https://stackoverflow.com/a/24795059/5470596

    【讨论】:

    • 虽然这确实是一个错误,但如果它产生问题中提到的诊断,我会感到非常惊讶。
    • 现在你只是从其他人的评论中复制粘贴。
    • @SergeyA 我错误地修复了 OP 的错误(自动)^^ 已修复。维护 VTC 错字。
    • @SergeyA 请不要痛苦。
    猜你喜欢
    • 1970-01-01
    • 2018-10-09
    • 2014-10-31
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2016-07-06
    • 1970-01-01
    相关资源
    最近更新 更多