我有一个“接口(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/