I would like to know how to convert function composition, but without using lambda. Below is the original code from https://stackoverflow.com/a/50035197.
template<class Root, class... Branches> auto comp(Root &&root, Branches &&... branches) {
return [root, branches...](auto &&...args) {
return root(branches(std::forward<decltype(args)>(args)...)...);
};
}
int f(int x, int y) { return x + y; }
int g(int x) { return x * 19; }
int h(int x) { return x + 2; }
#include <iostream>
int main() {
auto fgh = comp(f, g, h);
std::cout << fgh(2) << '\n';
}
I tried to mimic the comp
function without using lambdas, but failed to compile:
template<class Root, class... Branches>
class compose2 {
Root root;
tuple<Branches...> branches;
public:
compose2(Root r, Branches... br) : root(r), branches(br...) {};
template <class... Args>
decltype(auto) operator()(Args... args) {
return root(branches((args)...)...); // compile error, because a tuple is not a parameter pack
}
};
I know that parameter pack cannot be a member variable, so my first thought was to use a tuple for storing the functors (branches
), but I'm stuck here. So the question is, how to expand branches
as in comp
?