3

In Java, you can do the following code:

Function<Integer, Integer> times2 = e -> e * 2;
Function<Integer, Integer> squared = e -> e * e; 
times2.andThen(squared).apply(4);  

What's C++'s equivalent of andThen() to coin/composite new functors? Thanks.

MarianD
  • 11,249
  • 12
  • 32
  • 51
Han XIAO
  • 996
  • 8
  • 17

2 Answers2

2

If you are open to using Boost, then Boost.HOF is what you need. HOF (Higher order functions) provides the compose function adapter with the following semantics

assert(compose(f, g)(xs...) == f(g(xs...)));

In your case, you will do

auto composed = compose(squared, times2);
auto result = composed(4);

Have a look at the documentation for details https://www.boost.org/doc/libs/1_68_0/libs/hof/doc/html/include/boost/hof/compose.html

lakshayg
  • 1,983
  • 2
  • 21
  • 33
0

Why not keep things simple?

int times2thenSquared(int x) {
    x = times2(x);
    return squared(x);
}

(can do it with lambda as well, if you want)

Anton Malyshev
  • 8,378
  • 2
  • 25
  • 44