简体   繁体   中英

C++ equivalent of Java's andThen() function to composite new function

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM