首页 > 解决方案 > C++ 等效于 Java 的 andThen() 函数来组合新函数

问题描述

在 Java 中,您可以执行以下代码:

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

C++andThen()与硬币/复合新仿函数的等价物是什么?谢谢。

标签: c++

解决方案


如果您愿意使用 Boost,那么 Boost.HOF 就是您所需要的。HOF(高阶函数)为compose函数适配器提供以下语义

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

在你的情况下,你会做

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

查看文档以了解详细信息https://www.boost.org/doc/libs/1_68_0/libs/hof/doc/html/include/boost/hof/compose.html


推荐阅读