How to apply a constexpr function over every element in a std::tuple?

Viewed 208

I have a constexpr auto my_tuple = std::make_tuple(a, b, c, d, e);. Now, I want to apply a constexpr function over every of its elements. I thought that I could do it like this:

template <typename... Types>
void constexpr apply_func_on_tuple(std::tuple<Types...> tpl) noexcept
{
    for (std::size_t i = 0; i < sizeof...(Types); ++i)
    {
        my_function(std::get<i>(tpl));
    }
}

But it doesn't work. I learned why I can't do it this way after reading this. Is there any other way to accomplish what I want fully at compile-time?

1 Answers

You can't use a regular for loop, but you can write a constexpr function that works just like a loop:

template <typename T, auto ...I, typename F>
constexpr void static_for_low(F &&func, std::integer_sequence<T, I...>)
{
    (void(func(std::integral_constant<T, I>{})) , ...);
}

template <auto N, typename F>
constexpr void static_for(F &&func)
{
    static_for_low(func, std::make_integer_sequence<decltype(N), N>{});
}

Then you can do following:

template <typename ...Types>
constexpr void apply_func_on_tuple(std::tuple<Types...> tpl) noexcept
{
    static_for<sizeof...(Types)>([&](auto index)
    {
        my_function(std::get<index.value>(tpl));
    });
}
Related