c++ - 来自 std::vector<std::function> 的函数组合

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

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

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

最佳答案

你可以这样做:

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

通过按值传递 vector ,您甚至不必将 SFINAE 用于先前的重载。

关于c++ - 来自 std::vector<std::function> 的函数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53403077/

相关文章:

c# - 当我在 c# 中的一个类中定义我的所有函数时,我是否在进行函数式编程?

c++ - clang 是否支持 "-fprofile-generate"和 "-fprofile-use"?

c++ - 卡萨布兰卡:在 linux centos 上的汇编错误 gcc 4.8.1

c++ - 将元组转换为字符串

compiler-construction - F# - 应用序列转换时的可变上下文

javascript - 如何将 shouldComponentUpdate 与 React Hooks 一起使用?

C++函数将字符串拆分为单词

c++ - 重载运算符不在方法中工作

c++ - 模板和常量类型?

c++ - 为什么从 std::istream 读取记录结构字段失败,我该如何解决?