c++ - 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()
与硬币/复合新仿函数的等价物是什么?谢谢。
解决方案
如果您愿意使用 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
推荐阅读
- javascript - 使用javascript获取html中的子节点和子子节点
- regex - 如何在 Nginx 中使用 mod_rewrite 进行多次查询
- java - JavaSE 的 `java.sql javax.sql` 和 JDBC 驱动程序之间有什么关系?
- postgresql - Postgres:返回记录-错误-查询没有结果数据的目的地
- ios - 为什么 Metal 没有 rgb8Unorm MTLPixelFormat?
- php - 在 PHP Slim 框架中找不到类
- javascript - 渲染函数(reactjs)出错?
- java - 出现错误:未找到应用程序,当我单击 android 应用程序中的主屏幕快捷方式时
- google-cloud-platform - 在运行实例中安装包
- xaml - WPF - MVVM - Combobox UserControl + ComboboxItem CustomControl