简体   繁体   中英

Function composition from std::vector<std::function>

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

You might do something like:

template <typename T>
std::function<T(T)> make_composite_function(std::vector<std::function<T(T)>> v)
{
    std::reverse(v.begin(), v.end());
    return [=](T t) {
        for (const auto& f : v) {
            t = f(t);
        }
        return t;
    };
}

Demo

You don't even have to use SFINAE for previous overloads by passing vector by value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM