Search code examples
c++c++11stdarray

Template class in std::array


Is it possible to add a template class inside std::array without specifying the typename? I mean.

template<typename T>
class MyClass
{
    ...
}

std::array<MyClass *> arr;

The reason is that I have a kind of storage that accepts all classes that derives from MyClass but the problem with the template class is that I need to specify the typename, then the class need to be like that:

class Storage
{
    ...
private:
    std::array<MyClass<TYPE GOES HERE> *> arr;
}

And I want something more or less like this:

class Storage
{
    ...
private:
    std::array<MyClass *> arr;
}

This way I can add any class that derives from MyClass.

Is there a way for doing that?


Solution

  • One option is to create a base class from which MyClass derives and let the array store pointers to the base class.

    struct MyBase
    {
       virtual ~Base() {}
    };
    
    template<typename T>
    class MyClass : public MyBase
    {
        ...
    }
    
    std::array<MyBase*> arr;