0

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

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

Is there another way of doing this?

  • `Any` is a template not a type. – Jason Nov 08 '22 at 05:40
  • You should declare the type of **Any** like **Any types[2]{anynumbre,any number}** , and do not miss this "**;**" – Mahdy.n Nov 08 '22 at 05:44
  • What if I have more classes derived from Any, like String, Float, etc. – Davit Baghdasaryan Nov 08 '22 at 05:46
  • @DavitBaghdasaryan You'll need to provide the template argument as you can't use `Any` as a type-specifier because it is not a type in the first place. This means you can use `Any` or `Any` etc. See this dupe also ["error: Expected a type, got 'classname'" in C++](https://stackoverflow.com/questions/2705707/error-expected-a-type-got-classname-in-c) – Jason Nov 08 '22 at 05:47
  • Is there a way of doing this without templates such that I can declare the array as Any but put derived classes in it and access data – Davit Baghdasaryan Nov 08 '22 at 05:49

1 Answers1

0

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.

Chris
  • 26,361
  • 5
  • 21
  • 42