c++ - 通过索引实现 'constexpr for'

标签 c++ for-loop c++20 constexpr

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))时.


对于 ,我们最接近 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/

相关文章:

java - 在浏览器历史记录系统中乘以 for 循环

C++ std::vector<std::string> 迭代器段错误

c++ - 如何使用多线程制作一个简单的 Qt 控制台应用程序?

javascript - 我如何将这个 for 循环变成 forEach 循环?

c++ - 如何用 C++20 协程说 Hello World?

c++ - 为什么这个常量初始化变量的 `std::is_constant_evaluated()` 是假的?

c++ - 如何保证使用编译时常量初始化堆栈变量

c++ - C++读取音频文件

c++ - 如何判断指针指向的地址是否为0x0?

python - 打印全名python的第一个字母