I have an "interface" as .h file that has a virtual method like this:
class ISomeInterface {
public:
virtual std::shared_ptr<Parent> getX() = 0;
}
now that parent is "abstract" and in the implementors of the interface I use an actual class. So I wanted to do this:
class Implementor : public ISomeInterface {
public:
std::shared_ptr<Child> getX() = { return this->x; }
}
But then I get:
Could not convert ‘((Implementor*)this)->Implementor::parent’ from ‘std::shared_ptr’ to ‘std::shared_ptr’
So, basically the std::shared_ptr is a wrapper and the compiler does not know how to come from wrapper<apple> to wrapper<fruit>, even though apple extends fruit.
How can I circumvent that behaviour?
Edit: Looks like this is still not possible in c++, as covariant types are only working for pointers/references, not inside wrappers like std::shared_ptr... a shame :(
You can't. Covariant return types only work for raw pointers and references because the compiler knows how they work. For this to work for arbitrary types the compiler would need to be able to be told "this is safe to use with covariant return types", like C# does with out T generic parameters, but there's no such feature in C++.
Unfortunately, you need to return std::shared_ptr<Parent> in Implementor.
You could satisfy both the virtual interface and provide additional information to those who have access to the derived class by having two member functions:
struct Implementor : ISomeInterface
{
shared_ptr<Parent> getX() override { return getX_fromImplementor(); }
shared_ptr<Child> getX_fromImplementor() // not virtual!
{
// real implementation here
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With