7

Right now, I have the following to apply two functions to a value and return a 2-value tuple:

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

I wanted to generalize this to N functions:

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

I know I probably need to use template recursion somehow, but I can't wrap my head around it. Any ideas?

1

1 Answer 1

6

It took me a while, but here it is (using 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)...};
    }
};

Someone had an (incomplete) answer before, but s/he erased it - that was my starting point. Anyway, thank you stranger! Thank you R. Martinho Fernandes too!

1
  • 2
    Well done! I did not post an answer before because I was at work, so I left the comment so someone would pick up from there. I am glad that was enough to get you to a solution. Nov 27, 2012 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.