std :: shared_ptr <Parent>到std :: shared_ptr <Child>

Sor*_*ona 2 c++ c++14

我有一个"接口"作为.h文件,有一个像这样的虚拟方法:

class ISomeInterface {
    public:
        virtual std::shared_ptr<Parent> getX() = 0;
}
Run Code Online (Sandbox Code Playgroud)

既然父是"抽象"的,在接口的实现者中我使用的是实际的类.所以我想这样做:

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

但后来我得到:

无法将'((Implementor*)this' - > Implementor :: parent'从'std :: shared_ptr'转换为'std :: shared_ptr'

因此,基本上在std :: shared_ptr的是一个包装和编译器不知道如何来自wrapper<apple>于wrapper<fruit>,即使苹果延伸水果.

我该如何规避这种行为?

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

mil*_*bug 5

你不能.协变返回类型仅适用于原始指针和引用,因为编译器知道它们是如何工作的.为了使其适用于任意类型,编译器需要能够被告知"使用协变返回类型是安全的",就像C#使用out T泛型参数一样,但C++中没有这样的功能.

不幸的是,你需要返回std::shared_ptr<Parent>在Implementor.