现在,我可以执行以下操作将两个函数应用于一个值并返回一个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_;
};

我想将其概括为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_;
};

我知道我可能需要以某种方式使用模板递归,但是我无法解决这个问题。有任何想法吗?

最佳答案

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

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

之前有人回答(不完整),但他/他删除了-这是我的出发点。无论如何,谢谢陌生人!也谢谢R. Martinho Fernandes!

关于c++ - 将函数元组应用于值并返回元组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13589867/

10-11 22:37
查看更多