Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a tuple of functions to a value and return a tuple

Tags:

c++

c++11

tuples

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?

like image 671
bruno nery Avatar asked Nov 27 '12 17:11

bruno nery


1 Answers

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!

like image 78
bruno nery Avatar answered Oct 20 '22 05:10

bruno nery