for (int i = 0; i < 5; ++i) {
std::get<i>(tuple);
}
这不会编译,因为 i
不是编译时常量。在 How can you iterate over the elements of an std::tuple? 和其他帖子上,我看到了递归或使用 std::apply
的答案,但那些失去了索引控制。我也不想将自己限制在 std::tuple
上。
每当我必须在编译时循环某些东西时,我必须停下来思考并做一些奇怪的事情,尤其是当我尝试实现非标准迭代(如反向、自定义增量)或在同一语句中涉及多个索引(如 std::get<i>(tuple) * std::get<i + 1>(tuple)
)时.
对于 c++20,我们最接近 constexpr for (int i = 0; i < 5; ++i)
的是什么?
最佳答案
可以制作 constexpr_for<N>(F&& function)
使用 std::index_sequence
的实现展开 Size
作为0, 1, ... N - 1
到模板化的 lambda 上,它使用 std::integral_constant
调用函数范围。此参数将结构的模板参数隐式转换为 size_t
通过其 constexpr operator value_type() const noexcept;
运营商。
#include <utility>
#include <type_traits>
template<size_t Size, typename F>
constexpr void constexpr_for(F&& function) {
auto unfold = [&]<size_t... Ints>(std::index_sequence<Ints...>) {
(std::forward<F>(function)(std::integral_constant<size_t, Ints>{}), ...);
};
unfold(std::make_index_sequence<Size>());
}
这会启用 std::get<i>
行为:
auto tuple = std::make_tuple(0ull, 1, 2.0, "3", '4');
constexpr size_t size = std::tuple_size_v<decltype(tuple)>;
constexpr_for<size>([&](auto i) {
std::cout << std::get<i>(tuple) << ' ';
});
//prints 0 1 2 3 4
与 [&]
捕获可以访问size
所以可以实现反向迭代:
constexpr_for<size>([&](auto i) {
std::cout << std::get<size - i - 1>(tuple) << ' ';
});
//prints 4 3 2 1 0
或者例如通过检查越界尝试来迭代奇数索引:
constexpr_for<size>([&](auto i) {
constexpr auto idx = (i * 2 + 1);
if constexpr (idx < size) {
std::cout << std::get<idx>(tuple) << ' ';
}
});
//prints 1 3
关于c++ - 通过索引实现 'constexpr for',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73630843/