简体   繁体   中英

std::array with unspecialized template class

Is it possible to pass somehow unspecialized template class as a template parameter to std::array? Something similar to that:

template <class T>
class Field{
};

std::array<Field> a;

Or I have to define some BaseField, and sublass it as a IntField, StringField, FloatField.... ?

You can write a template that takes a template as a parameter (aka, a template template parameter). The template has to be written specifically to take a template as a parameter to allow it though, and std::array isn't specified to do that.

You can get pretty close with C++11, using an alias template:

template <typename T>
struct Field {}; 

template <typename T>
using FieldArray5 = std::array<Field<T>,5>;

int main() {

  FieldArray5<int> a0;

}

But bear in mind that std::array needs a template argument for the size too.

If you want an std::array to hold different types, it can only be done through polymorphism. You can also use boost::any that hides that polymorphism from you but still implements it.

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