来自std :: vector <std :: function>的函数组成

时间:2018-11-20 23:18:19

标签: c++ c++11 functional-programming

扩展@nes代码(https://codereview.stackexchange.com/questions/67241/function-composition-using-stdbind)可以编辑代码,以便make_composition_function的输入可以是函数的向量,而不是作为单独参数的函数。

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

1 个答案:

答案 0 :(得分:3)

您可能会做类似的事情:

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

通过按值传递向量,您甚至不必为以前的重载使用SFINAE。