I have a constexpr size_t
array whose members will be passed to the template parameters of a class that gets initialized, iterating over the array to construct and use several differently templated objects. Here's the general idea:
template <size_t N>
class Foo
{
// magic
};
constexpr size_t c_arr[] = { 2, 5, 3, 2 };
for (int i = 0; i < 4; i++)
{
Foo<c_arr[i]> foo;
foo.bar();
}
However, this will raise the following error:
templ_arr.cpp: In function ‘int main()’:
templ_arr.cpp:56:21: error: the value of ‘i’ is not usable in a constant expression
Foo<c_arr[i]> foo;
^
templ_arr.cpp:51:14: note: ‘int i’ is not const
for (int i = 0; i < 3; i++)
^
templ_arr.cpp:56:20: note: in template argument for type ‘long unsigned int’
Foo<c_arr[i]> foo;
I can't seem to find a way to use const_cast
on i
to allow it to be used inside the parameter, nor can I do something like this to get around it, as it gives me the same error:
for (int i = 0; i < 4; i++)
{
const int j = i;
Foo<c_arr[j]> f;
foo.bar();
}
What am I doign wrong, and how can I get around this?