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
  • 13,096
  • 12
  • 42
  • 54
Han XIAO
  • 1,148
  • 9
  • 20

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
  • 2,053
  • 2
  • 20
  • 34
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,686
  • 2
  • 27
  • 45