Stack Danny
Stack Danny

Reputation: 8126

Achieving 'constexpr for' with indexing

for (int i = 0; i < 5; ++i) {
    std::get<i>(tuple);
}

this doesn't compile, since i is not a compile time constant. On How can you iterate over the elements of an std::tuple? and other posts I see answers of recursion, or using std::apply, but those lose the index control. I also don't want to limit myself soley on std::tuple.


Whenever I have to loop over something at compile time I have to stop and think and do weird things especially when I try to achieve non-standard iterations like reverse, custom increment, or involve multiple indices in the same statements such as std::get<i>(tuple) * std::get<i + 1>(tuple).


with what is the closest we can have to a constexpr for (int i = 0; i < 5; ++i)?

Upvotes: 3

Views: 493

Answers (1)

Stack Danny
Stack Danny

Reputation: 8126

It is possible to make a constexpr_for<N>(F&& function) implementation that uses std::index_sequence to expand the Size as 0, 1, ... N - 1 onto a templated lambda, which calls the function with a std::integral_constant parameter. This parameter implicitly converts the struct's template argument to size_t via its constexpr operator value_type() const noexcept; operator.

#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>());
}

This enables the std::get<i> behaviour:

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

with the [&] capture there is access to size so reverse-iterating can be achieved:

constexpr_for<size>([&](auto i) {
    std::cout << std::get<size - i - 1>(tuple) << ' ';
});
//prints 4 3 2 1 0

or e.g. iterate over odd indices by checking against out of bounds attempts:

constexpr_for<size>([&](auto i) {
    constexpr auto idx = (i * 2 + 1);
    if constexpr (idx < size) {
        std::cout << std::get<idx>(tuple) << ' ';
    }
});
//prints 1 3

Upvotes: 7

Related Questions