Reputation: 7049
I have a non-type template class 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
Upvotes: 1
Views: 287
Reputation: 4025
template <int n>
class Foo : public Ifoo {
public:
Foo(){}
};
IFoo* myArray[] = {..
Upvotes: 1
Reputation: 62532
As had been mentioned, Foo<1>
is a different type to Foo<2>
etc etc, so you can't store them in an array.
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)};
Upvotes: 1
Reputation: 218268
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*
).
You may store them in a std::tuple
:
auto foos = std::make_tuple(Foo<1>() , Foo<2>() , Foo<3>());
Upvotes: 6