【问题标题】:How to apply a constexpr function over every element in a std::tuple? [duplicate]如何对 std::tuple 中的每个元素应用 constexpr 函数? [复制]
【发布时间】:2019-06-29 18:28:08
【问题描述】:

我有一个constexpr auto my_tuple = std::make_tuple(a, b, c, d, e);。现在,我想在其每个元素上应用constexpr 函数。我以为我可以这样做:

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

但它不起作用。在阅读this 后,我明白了为什么我不能这样做。有没有其他方法可以在编译时完成我想要的完全?

【问题讨论】:

标签: c++ templates metaprogramming stdtuple


【解决方案1】:

您不能使用常规的for 循环,但可以编写一个像循环一样工作的constexpr 函数:

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>{});
}

然后您可以执行以下操作:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-27
    • 2019-05-04
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多