[英]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.