c++ - std::shared_ptr<Parent> 到 std::shared_ptr<Child>

标签 c++ c++14

我有一个“接口(interface)”作为 .h 文件,它有一个像这样的虚拟方法:

class ISomeInterface {
    public:
        virtual std::shared_ptr<Parent> getX() = 0;
}

现在 parent 是“抽象的”,在接口(interface)的实现者中我使用了一个实际的类。所以我想这样做:

class Implementor : public ISomeInterface {
    public:
        std::shared_ptr<Child> getX() = { return this->x; }
}

但后来我得到:

Could not convert ‘((Implementor*)this)->Implementor::parent’ from ‘std::shared_ptr’ to ‘std::shared_ptr’

所以,基本上 std::shared_ptr 是一个包装器,编译器不知道如何来自 wrapper<apple>wrapper<fruit> ,即使苹果延长了果实。

我怎样才能规避这种行为?

编辑: 看起来这在 C++ 中仍然是不可能的,因为协变类型仅适用于指针/引用,而不适用于像 std::shared_ptr 这样的包装器...真可惜 :(

最佳答案

你不能。协变返回类型只适用于原始指针和引用,因为编译器知道它们是如何工作的。为了使其适用于任意类型,编译器需要能够被告知“这可以安全地用于协变返回类型”,就像 C# 对 out T 所做的那样。泛型参数,但 C++ 中没有此功能。

很遗憾,您需要返回 std::shared_ptr<Parent>Implementor .

关于c++ - std::shared_ptr<Parent> 到 std::shared_ptr<Child>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43127045/

相关文章:

c++ - 如何消除此枚举到字符串映射代码的样板?

c++ - 防止别名到别名重新定义 C++

c++ - 创建我的第一个程序来显示生日

c++ - 如何对两个指针指向的变量使用 delete?

c++ - 标准库中有哪些函数可以通过编程技巧更快地实现?

c++ - 无限数量的复选框

c++ - 正确访问 const 一行特征矩阵

c++ - 是否使用静态 constexpr 变量 odr?

C++ va_list 返回奇数

c++ - PSN_QUERYCANCEL 不关闭属性表