Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 558
Han XIAO Avatar asked Dec 29 '25 23:12

Han XIAO


1 Answers

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

like image 124
lakshayg Avatar answered Jan 01 '26 14:01

lakshayg