将一个函数元组应用于一个值并返回一个元组

bru*_*ery 6 c++ tuples c++11

现在,我有以下两个函数应用于一个值并返回一个2值元组:

template<typename F1, typename F2>
class Apply2
{
public:
    using return_type = std::tuple<typename F1::return_type, typename F2::return_type>;

    Apply2(const F1& f1, const F2& f2) : f1_(f1), f2_(f2) {}

    template<typename T> return_type operator()(const T& t) const
    {
        return std::make_tuple(f1_(t), f2_(t));
    }

protected:
    const F1& f1_;
    const F2& f2_;
};
Run Code Online (Sandbox Code Playgroud)

我想把它推广到N个函数:

template<typename ...F>
class ApplyN
{
public:
    using return_type = std::tuple<typename F::return_type...>;

    ApplyN(const std::tuple<F...>& fs) : functions_(fs) {}

    template<typename T> return_type operator()(const T& t) const
    {
        return ???;
    }

protected:
    std::tuple<F...> functions_;
};
Run Code Online (Sandbox Code Playgroud)

我知道我可能需要以某种方式使用模板递归,但我无法绕过它.有任何想法吗?

bru*_*ery 6

我花了一段时间,但在这里(使用索引):

template<typename ...F>
class ApplyN
{
public:
    using return_type = std::tuple<typename F::return_type...>;

    ApplyN(const F&... fs) : functions_{fs...} {}

    template<typename T> return_type operator()(const T& t) const
    {
        return with_indices(t, IndicesFor<std::tuple<F...> >{});
    }

protected:
    std::tuple<F...> functions_;

    template <typename T, std::size_t... Indices>
    return_type with_indices(const T& t, indices<Indices...>) const
    {
        return return_type{std::get<Indices>(functions_)(t)...};
    }
};
Run Code Online (Sandbox Code Playgroud)

之前有人有一个(不完整的)答案,但他/她删除了它——那是我的起点。不管怎样,谢谢陌生人!也感谢 R. Martinho Fernandes!

  • 做得好!我之前没有发布答案,因为我在工作,所以我留下了评论,以便有人从那里接听。我很高兴这足以让 *你* 找到解决方案。 (2认同)