3

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?

wk_j
  • 105
  • 6
  • 2
    out of curiosity: why without using lambda expressions? – 463035818_is_not_an_ai Mar 18 '21 at 15:43
  • Without lambda... then can you use Boost? – Eljay Mar 18 '21 at 15:44
  • I would like to understand how it can be possible without using bind in boost, because from my understanding lambda is a syntactic sugar for a functor. – wk_j Mar 18 '21 at 16:00
  • 1
    Ok, I *think* you may find some progress in [this question](https://stackoverflow.com/questions/60704441/unpacking-tuples-variadic-template-arguments). If you problem really stems from unpacking parameters stored in a tuple, there's going to be some wrapping/unwrapping involved, but it may help. – WhozCraig Mar 18 '21 at 16:12
  • they are, kind of, the tricky part is the capture – 463035818_is_not_an_ai Mar 18 '21 at 16:24

0 Answers0