I want to fill a template with some integers from an array but this doesn't seem to be allowed in C++. An example:
I define a constant array with Integers.
const int array[4] = {0, 1, 2, 3};
My template works like that:
template<int T> TestClass ...
In the following, the first way is no problem, but the second way does not compile:
TestClass<12> ... // works
TestClass<array[0]> ... // does not work
The compiler says that the operator '[' is not allowed in a temlate. But what is the reason for that and how can I solve this situation elegantly? Is it also possible to use a counter i
of a for
-loop to choose the Integer of the array, like:
TestClass<array[i]>
Turn your array to a constexpr
variable:
constexpr int array[4] = {0, 1, 2, 3};
or even better:
constexpr std::array<int, 4> myArray{0, 1, 2, 3};
Since your array will be constexpr
, it's usage will be valid at compile-time.
Be sure to enable c++14 for the std::array
version.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments