Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
{
public:
    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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading