使用非常量变量作为 constexpr 数组的索引以传递给模板参数
Using non-const variable as index to constexpr array to pass to template parameter
我有一个 constexpr size_t
数组,其成员将被传递给 class 的模板参数,该数组被初始化,遍历该数组以构造和使用几个不同的模板化对象。这是总体思路:
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();
}
但是,这会引发以下错误:
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
上使用 const_cast
以允许它在参数内部使用的方法,我也不能做这样的事情来绕过它,因为它给了我同样的错误:
for (int i = 0; i < 4; i++)
{
const int j = i;
Foo<c_arr[j]> f;
foo.bar();
}
我做错了什么,我该如何解决这个问题?
如果要将 values 用作模板参数,请使用 std::integer_sequence
template <size_t N>
class Foo
{
public:
void bar() {}
};
template<std::size_t ...I>
void foo_bar(std::index_sequence<I...>) {
int dummy[] = { (Foo<I>{}.bar(), 0) ... };
// ((Foo<I>{}.bar()), ...); if using C++17 or above
}
int main() {
constexpr std::index_sequence<2, 5, 3, 2> id;
foo_bar(id);
}
我有一个 constexpr size_t
数组,其成员将被传递给 class 的模板参数,该数组被初始化,遍历该数组以构造和使用几个不同的模板化对象。这是总体思路:
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();
}
但是,这会引发以下错误:
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
上使用 const_cast
以允许它在参数内部使用的方法,我也不能做这样的事情来绕过它,因为它给了我同样的错误:
for (int i = 0; i < 4; i++)
{
const int j = i;
Foo<c_arr[j]> f;
foo.bar();
}
我做错了什么,我该如何解决这个问题?
如果要将 values 用作模板参数,请使用 std::integer_sequence
template <size_t N>
class Foo
{
public:
void bar() {}
};
template<std::size_t ...I>
void foo_bar(std::index_sequence<I...>) {
int dummy[] = { (Foo<I>{}.bar(), 0) ... };
// ((Foo<I>{}.bar()), ...); if using C++17 or above
}
int main() {
constexpr std::index_sequence<2, 5, 3, 2> id;
foo_bar(id);
}