简体   繁体   English

非类型模板数组?

[英]Array of non-type template?

I have a non-type template class Foo: 我有一个非类型的模板类Foo:

template <int n>
class Foo {
public:
  Foo(){}
};

How can I store multiple instances of that class in one array? 如何在一个数组中存储该类的多个实例? (When the instances all have different template values.) (当所有实例具有不同的模板值时。)

This, however, does not work: 但是,这不起作用:

Foo<int> myArray[] = {Foo<1>() , Foo<2>() , Foo<3>()};

Compiler error is: template argument for non-type template parameter must be an expression 编译器错误是: 非类型模板参数的模板参数必须为表达式

Foo<1> is not the same type as Foo<2> (and so on), so you can't store them in a array (if they derived from FooBase , you may have an array of FooBase* ). Foo<1>Foo<2>类型不同(依此类推),因此您不能将它们存储在数组中(如果它们是从FooBase派生的,则可能有一个FooBase*数组)。

You may store them in a std::tuple : 您可以将它们存储在std::tuple

auto foos = std::make_tuple(Foo<1>() , Foo<2>() , Foo<3>());
template <int n>
class Foo : public Ifoo {
public:
  Foo(){}
};

IFoo* myArray[] = {..

As had been mentioned, Foo<1> is a different type to Foo<2> etc etc, so you can't store them in an array. 如前所述, Foo<1>是与Foo<2>等不同的类型,因此您不能将它们存储在数组中。

To get around this you can de-template the class and make the integer a constructor argument instead: 为了解决这个问题,您可以取消类的模板并将整数作为构造函数参数:

class Foo {
public:
  Foo(int n){}
};

Foo myArray[] = {Foo(1) , Foo(2) , Foo(3)};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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