Nick
Nick

Reputation: 43

How to inherit template class in C++?

I am the Java guy and try to write inheritince over class template and I got a lot of error like: template specialization requires 'template<>' or use of class template 'array' requires template arguments. Can you guys help me to correct my faults about code or way of thinking? I have classes like this:

template <typename T>

class array {
public:
virtual void randomFunction() = 0;

protected:
T* values;
int size; // number of values
};

Here intArray.h

class intArray: public array<int>{
public:
  intArray();
  void randomFunction();
private:
};

Here intArray.cpp

intArray::intArray() {
this->size = 1;
this->values = new int[1];
}

void intArray::randomFunction() {
this->values[0] = 5; 
}

What I want is iterate over these objects like:

int main() {
  vector<array> arrayList;
  arrayList.push_back(intArray());
  arrayList.push_back(doubleArray());
  arrayList.push_back(stringArray());

  anotherFunction(&arrayList);
}

void anotherFunction(vector<array> *list) {
for(array a: (*list)) {
  a.randomFunction();
}
}

Upvotes: 1

Views: 89

Answers (1)

Since your array is a class template, this vector<array> is not a valid type definition. As std::vector expects a type parameter.

If you are looking to accomplish type erasure, then that requires your class template to itself inherit from a base:

class array_base {
  virtual void randomFunction() = 0;
  virtual ~array_base();
};

template <typename T>
class array : public array_base {
  // As before
};

That still isn't enough, since C++ isn't Java. We deal with objects, and to deal with them polymorphically, we need to explicitly use (smart-)pointers or references.

Bearing that in mind, your vector should now become this:

std:vector<std::unique_ptr<array_base>> arrayList;
arrayList.emplace_back(std::make_unique<intArray>());

Upvotes: 4

Related Questions