Home > Blockchain >  Why std::shared_ptr doesn't work with base template classes?
Why std::shared_ptr doesn't work with base template classes?

Time:04-05

First let me show you the inheritance structure:

template <class Type>
class Base {
public:
    Base() {}
    virtual bool verify() const = 0;
};

class Derived : public Base<int> {

public:
    Derived() : Base<int>::Base() {}
    virtual bool verify() const override;
};

So, the base class for Derived is Base<int>.

I'm trying to define a template overload of the "|" operator:

template<class Type>
std::shared_ptr<Base<Type>> operator|(std::shared_ptr<Base<Type>> p1, std::shared_ptr<Base<Type>> p2)
{
    return std::shared_ptr<Base<Type>>();
}

And, if I write something like:

std::shared_ptr<Derived> d;
std::shared_ptr<Base<int>> bInt;
auto result = d | bInt;

I'll get an error like:

C missing "|" operator corresponding to these operands: std::shared_ptr<Derived> | std::shared_ptr<Base<int>>

But, if I explicitly specify the type of the base class when overloading, everything will work correctly:

std::shared_ptr<Base<int>> operator|(std::shared_ptr<Base<int>> p1, std::shared_ptr<Base<int>> p2)
{
    return std::shared_ptr<Base<int>>();
}

How can I make the templated overload work?

CodePudding user response:

you have to either specify operator for a Derived class, or to save both of your variables in the pointer of Base:

std::shared_ptr<Base<int>> d = std::make_shared<Derived>();
std::shared_ptr<Base<int>> bInt;
auto res = d | bInt;
  • Related