function composition in C++ / C++11

前端 未结 7 1509
北荒
北荒 2020-12-01 09:38

I am currently coding some cryptographic algorithms in C++11 that require a lot of function compositions. There are 2 types of composition I have to deal with :

7条回答
  •  感情败类
    2020-12-01 09:58

    Here is a simple c++14 solution (it may probably be re-written to c++11):

    #include 
    
    // base condition
    template 
    auto compose(F&& f)
    {
        return [a = std::move(f)](auto&&... args){
            return a(std::move(args)...);
        };
    }
    
    // recursive composition
    // from compose(a, b, c...) to compose(ab, c...)
    template 
    auto compose(F1&& f1, F2&& f2, Fs&&... fs)
    {
        return compose(
            [first = std::move(f1), second = std::move(f2)]
            (auto&&... args){
                return second(first(std::move(args)...));
            },
            std::move(fs)...
        );
    }
    

    Possible usage:

    int main()
    {
    const auto f = compose(
      [](const auto n){return n * n;},
      [](const auto n){return n + 2;},
      [](const auto n){return n + 2;}
    );
    std::cout << f(10) << std::endl; // outputs 104
    }
    

    Here is a link to the repo with a few more examples: https://github.com/nestoroprysk/FunctionComposition

提交回复
热议问题