C++ create an array with type of template base class without specifying the template argument

For example I have some base type Any

template<typename T>
class Any
    T data;
    Any(T data) { this->data = data; }
    // some other function signatures using data

class Number : public Any<int>
    // functions defining all functions like substracting etc.

And more classes deriving Any

Now in main function I want to create an array of Any

int main()
    Any types[2] { Number(1), Number(3) }; // doesnt work

Is there another way of doing this?

>Solution :

Let’s say you have:

class A : public Any<int> { };

class B : public Any<std::string> { };

class C : public Any<double> { };

Objects of type A, B, and C are not subclasses of Any because Any is a template. Rather they are subclasses of Any<int>, Any<std::string> and Any<double>, respectively and as such do not share a common parent class.

You may wish to read up on std::variant.

Leave a Reply