neevek
neevek

Reputation: 12148

Assign derived template class to base class template

This seems not possible, but I think it is reasonable to have what I looking for. I have the following code:

template <typename T>
class Data{
  T getData() {
    return data;
  }
  private:
    T data;
};

template <typename T>
class Base : public Data<T> {
  public:
    void someCommonAction() { }
};

class DerivedInt : public Base<int> {
};

class DerivedFloat : public Base<float> {
};

I want to assign derived objects to the Base class, but the compiler complains that template argument is required for Base:

Base b = DerivedInt{};

I understand that the Base class template itself is not a complete class, but requirements like this is quite reasonable to me. Are there any alternatives to achieve what I want?

Upvotes: 0

Views: 329

Answers (1)

max66
max66

Reputation: 66230

understand that the Base class template itself is not a complete class, but requirements like this is quite reasonable to me. Are there any alternatives to achieve what I want?

Reasonable but you need template argument deduction; so starting from C++17 you can add something as

template <typename T>
Base(Base<T>) -> Base<T>;

and

Base b = DerivedInt{};

should work.

Off topic: observe that in

template <typename T>
class Data{
  T getData() {
    return data;
  }
  private:
    T data;
};

the getData() method is private

I suppose your intention was make it public

template

class Data{
  public:
     T getData() {
       return data;
     }
  private:
    T data;
};

or make Data a struct

Upvotes: 1

Related Questions