简体   繁体   中英

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?

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;

The reason is that I have a kind of storage that accepts all classes that derives from MyClass

You cannot create a class that derives from MyClass , you can create a class that derives from MyClass<int> for example etc. So solutions that I see are:

  • Make template MyClass derived from non template BaseClass and keep pointer to BaseClass
  • Make MyClass non template and create a template class that derives from it. (this is technically the same as the first)
  • Keep void * and cast it to specific MyClass<> on usage, this is error prone though and not recommended.
  • Use boost::any or boost::variant (using boost::variant would be pretty complicated though

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM