lundi 17 décembre 2018

C++: unique_ptr polymorphism for template classes derived from a non-template base class

I have the following class:

class Base {
public:
    Base() = default;
    virtual ~Base() {};
}

And, let's say I have a unique_ptr to this class, aka:

using BasePtr = std::unique_ptr<Base>;

Now, let's assume I have a template class that inherits from the base class.

template <typename T>
class Derived : public Base {
public:
      Derived() = default;
      Derived(const T x) : some_variable(x) {};
      ~Derived() override {};
       void hello() { std::cout << some_variable << std::endl; }
 private:
       T some_variable;
}

For arguments sake, let's say I have a factory method that creates a unique_ptr to some new instance, such as:

template <typename T>
auto make_class(const T& x) -> BasePtr {
    return std::unique_ptr<Derived<T> >(new Derived<T>(x));
}

If I try to build this:

int main() {
    auto ptr = make_class<int>(5);
    if (ptr) {
         ptr->hello();
    }
    return 0;
}

With C++11, this results in a compile error (saying that Base does not have a hello() method), because it seems that the actual instance stored in the unique_ptr is a Base, not a Derived.

Based on my understanding (at least if Derived wasn't templated), this should not be an issue. What's happening here?

Aucun commentaire:

Enregistrer un commentaire