【问题标题】:Create tuple from result of functions in callable variadic tuple从可调用可变元组中的函数结果创建元组
【发布时间】:2019-09-05 07:40:13
【问题描述】:

我正在尝试编写以下内容:我有一个包含 N 个函数的元组作为输入。所有这些函数都可以有不同的返回类型,但只接受一个相同类型的参数。我想将每个函数调用给定参数的结果放入一个元组中。

template <typename AttributeType, typename ...Functions>
auto f(std::tuple<Functions...> &tupleOfFunctions, const AttributeType &attr)
{
  return std::make_tuple(std::get<0>(tupleOfFunctions)(attr), std::get<1>(tupleOfFunctions)(attr), …, std::get<N>(tupleOfFunctions)(attr));
}

【问题讨论】:

    标签: c++ tuples variadic


    【解决方案1】:

    你去吧:

    template <typename AttributeType, typename ...Functions>
    auto f(std::tuple<Functions...> &tupleOfFunctions, const AttributeType &attr)
    {
        return std::apply(
            [&](auto &... f) { return std::tuple{f(attr)...}; },
            tupleOfFunctions
        );
    }
    

    Live demo

    这可以被调整以透明地处理引用返回函数:

    template <typename AttributeType, typename ...Functions>
    auto f(std::tuple<Functions...> &tupleOfFunctions, const AttributeType &attr)
    {
        return std::apply(
            [&](auto &... f) { return std::tuple<decltype(f(attr))...>{f(attr)...}; },
            //                                  ^^^^^^^^^^^^^^^^^^^^^^
            tupleOfFunctions
        );
    }
    

    【讨论】:

    • 您能否在答案中添加更多解释?为什么要使用std::apply?谢谢。
    • @Pierre 好吧,这更容易。它将tupleOfFunctions的元素绑定到auto &amp;... f参数包,然后我们可以直接展开。其他解决方案是可能的,但它们需要更多的工作来完成相同的扩展(通常使用辅助函数和 std::index_sequence)。
    • std::tuple&lt;decltype(f(attr))...&gt;{f(attr)...} 处理引用类型。
    • @Jarod42 我看到了你之前的评论并且有同样的想法(因为,我猜你已经意识到,std::forward_as_tuple 会产生对过期prvalues 的悬空引用)。感谢您的想法:)
    • 是的,std::forward_as_tuple 不能使用,所以我删除了新的评论。
    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2021-01-12
    • 2016-12-04
    相关资源
    最近更新 更多