嵌套静态循环因constexpr无法捕获而无法工作 [英] Nested static loop fails to work due to constexpr uncapturable
问题描述
我有这个 static_loop
构造,用于在循环展开时进行类型调度。
I have this static_loop
construct that is used for type dispatching over loop unrolling.
template <std::size_t n, typename F> void static_loop(F&& f) {
static_assert(n <= 8 && "static loop size should <= 8");
if constexpr (n >= 8)
f(std::integral_constant<size_t, n - 8>());
if constexpr (n >= 7)
f(std::integral_constant<size_t, n - 7>());
if constexpr (n >= 6)
f(std::integral_constant<size_t, n - 6>());
if constexpr (n >= 5)
f(std::integral_constant<size_t, n - 5>());
if constexpr (n >= 4)
f(std::integral_constant<size_t, n - 4>());
if constexpr (n >= 3)
f(std::integral_constant<size_t, n - 3>());
if constexpr (n >= 2)
f(std::integral_constant<size_t, n - 2>());
if constexpr (n >= 1)
f(std::integral_constant<size_t, n - 1>());
}
template <typename T> constexpr size_t tupleSize(T) { return tuple_size_v<T>; }
struct A {
int a;
int b;
void run() {
auto ab = std::make_tuple(std::ref(a), std::ref(b));
static_loop<2>([&](auto i) {
std::get<i>(ab) = i;
static_loop<2>([&](auto j) { std::get<i * j>(ab) = i; });
// static_loop<2>([&, i = std::integral_constant<size_t, i>()](auto j) { std::get<i * j>(ab) = i; });
});
std::cout << a << " " << b << std::endl;
}
};
但是在执行嵌套循环时它不会编译。我假设 i
和 j
都是 constexpr
因此 i * j
在 std :: get<>
中有效,但是,编译器似乎不允许这样做。是否可以在内部lambda中将 i
捕获为constexpr?
However it doesn't compile when doing nested loops. I'd assume i
and j
are both constexpr
thus i * j
is valid in std::get<>
, however, compiler seems not allowing this. Is it possible to capture i
as constexpr in the inner lambda?
完整示例位于 godbolt 以及错误消息。
Full example is at godbolt along with the error messages.
推荐答案
static_loop<2>([&](auto i) {
std::get<i>(ab) = i;
static_loop<2>([&](auto j) { std::get<i * j>(ab) }
}
IDE会正确地为您强调错误。 i * j
是两个变量的乘积,它不是编译时常量。
The IDE correctly underlines the error for you. i * j
is a multiplication of two variables, it is not a compile-time constant.
如果切换到模板参数,则可以嵌套循环而不是函数参数。
You can nest loops if you switch to template parameters rather than function arguments.
这篇关于嵌套静态循环因constexpr无法捕获而无法工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!