c++ - 如何从仿函数元组返回返回值元组?

标签 c++ c++17

    namespace easy_random {

    template<typename First_T>
    auto make_tuple_of_rands(First_T first) {
        return std::make_tuple(first());
    }

    template<typename First_T, typename... Rest_T>
    auto make_tuple_of_rands(First_T first, Rest_T... rest) {
        return std::tuple_cat(make_tuple_of_rands(first),make_tuple_of_rands(rest...));
    }

    template<typename First_T>
    auto make_tuple_of_n_rands(std::size_t n, First_T first) {
        return std::make_tuple(first(n));
    }

    template<typename First_T, typename... Rest_T>
    auto make_tuple_of_n_rands(std::size_t n, First_T first, Rest_T... rest) {
        return std::tuple_cat(make_tuple_of_n_rands(n, first), make_tuple_of_n_rands(n, rest...));
    }



    template<typename... RandStreamTypes>
    class multi_rand_stream {
        std::tuple<RandStreamTypes...> streams;
    public:
        explicit multi_rand_stream(RandStreamTypes... args);

        explicit multi_rand_stream(std::tuple<RandStreamTypes...> &args);

        auto operator()();

        auto operator()(std::size_t n);
    };

    template<typename... RandStreamTypes>
    multi_rand_stream<RandStreamTypes...>::multi_rand_stream(RandStreamTypes... args) : streams(args...) {}

    template<typename... RandStreamTypes>
    multi_rand_stream<RandStreamTypes...>::multi_rand_stream(std::tuple<RandStreamTypes...> &args) : streams(args) {}

    template<typename... RandStreamTypes>
    auto multi_rand_stream<RandStreamTypes...>::operator()() {
        return std::apply(make_tuple_of_rands, streams);
    }

    template<typename... RandStreamTypes>
    auto multi_rand_stream<RandStreamTypes...>::operator()(std::size_t n) {
        return std::apply(make_tuple_of_n_rands, std::tuple_cat(std::make_tuple(n), streams));
    }
}

我希望能够返回一个元组,该元组由将 tup 的成员作为仿函数运行时的返回值组成。

我目前不知道该怎么做。我已尝试将应用和递归与 tuple_cat 结合使用,但在推断函数的模板类型时遇到了问题。

编辑:包括我正在尝试实现的完整类,也许这会暴露我的错误。

最佳答案

来自上面评论的答案:我会简单地使用 std::apply() 将元组展开为可变参数 lambda。然后您可以在那里接收元组元素作为参数包,您可以将其扩展为一个初始化列表,该列表通过调用每个元素生成一个新的元组:

template<typename... Ts>
class multi_functor
{
    std::tuple<Ts...> tup;

public:
    auto operator()()
    {
        return std::apply([](auto&&... args)
        {
            return std::tuple { args()... };
        }, tup);
    }
};

关于c++ - 如何从仿函数元组返回返回值元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51661775/

相关文章:

c++ - 具有由整数确定的固定数量参数的函数

c++ - 结构绑定(bind) : binding to public data members (inherited base class )

c++ - 在googlemock中模拟文件写入过程

c++ - 如果我输入字母而不是数字,为什么会出现无限循环?

c++ - 将指针作为参数传递给从属 dll 对象大小错误

c++ - 是否有一种快速算法计算能力是二分之一的倍数?

c++ - 并行 SURF 和 SIFT 计算

c++ - 如何判断是使用<filesystem>还是<experimental/filesystem>?

c++ - 实现多态性

c++ - 无法推导 std::function 模板参数