mardi 20 novembre 2018

Function composition from std::vector

Expanding on @nes code (https://codereview.stackexchange.com/questions/67241/function-composition-using-stdbind), is there a way to edit the code, so that the input to make_composition_function could be a vector of functions instead of functions as separate arguments.

#include <iostream>
#include <functional>
#include <vector>

// traits to infer the return type of recursive binds
template<typename... Fn>
struct composite_function_traits;

// bind a single function with a placeholder
template<typename F1>
struct composite_function_traits<F1> { typedef decltype(std::bind(std::declval<F1>(), std::placeholders::_1)) type; };

template<typename F1>
typename composite_function_traits<F1>::type make_composite_function(F1&& f1)
{
    return std::bind(std::forward<F1>(f1), std::placeholders::_1);
}

// recursively bind multiple functions
template<typename F1, typename... Fn>
struct composite_function_traits<F1, Fn...> { typedef decltype(std::bind(std::declval<F1>(), std::declval<typename composite_function_traits<Fn...>::type>())) type; };

template<typename F1, typename... Fn>
typename composite_function_traits<F1, Fn...>::type make_composite_function(F1&& f1, Fn&&... fn)
{
    return std::bind(std::forward<F1>(f1), make_composite_function(std::forward<Fn>(fn)...));
}

int main() {
    using namespace std;
    auto f1 = [] (int x) { cout << "f1" << endl; return x; };
    auto f2 = [] (int x) { cout << "f2" << endl; return x; };
    auto f3 = [] (int x) { cout << "f3" << endl; return x; };
    // this works -> int y = make_composite_function(f1, f2, f3)(1);

    // what I would like to be able to do   
    std::vector<std::function<int(int)>> funvec;
    funvec.push_back(f1);
    funvec.push_back(f2);
    funvec.push_back(f3);
    int y = make_composite_function(funvec)(1);

    // print result
    cout << y << endl;
}

Aucun commentaire:

Enregistrer un commentaire