Home > Blockchain >  How to nest and combine a bunch of functions?
How to nest and combine a bunch of functions?

Time:11-02

Like I have a bunch of functions, f, g, h.... How to easily combine them to new_func(x) = f(g(h(x)))? For convenience, we can assume that the last function has no parameters and that the other functions can be called nested.

Could the template parameter package achieve this?

update:

Actually, I want a way can give me a combination of functions, like

some_nest_method(f, g, h)(x) == f(g(h(x)))

CodePudding user response:

you can merge the function recursively

something like this

template <typename F>
F combine(F f){return f;}

template <typename F, typename...Fs>
auto combine(F f, Fs ...fs){
    auto rest = combine(fs...);
    return [=](auto arg){
        return f(rest(arg));
    };
}

https://godbolt.org/z/EzqjKr4q5

  • Related