[英]C++ equivalent of Java's andThen() function to composite new function
在Java中,您可以执行以下代码:
Function<Integer, Integer> times2 = e -> e * 2;
Function<Integer, Integer> squared = e -> e * e;
times2.andThen(squared).apply(4);
什么是C ++相当于andThen()
来硬币/复合新的andThen()
函数? 谢谢。
如果您愿意使用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
为什么不保持简单?
int times2thenSquared(int x) {
x = times2(x);
return squared(x);
}
(如果你愿意的话,也可以用lambda做)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.