【问题标题】:C++ equivalent of Java's andThen() function to composite new functionC++ 等效于 Java 的 andThen() 函数来复合新函数
【发布时间】:2018-08-22 15:02:20
【问题描述】:

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

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

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

【问题讨论】:

标签: c++


【解决方案1】:

如果您愿意使用 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

【讨论】:

    【解决方案2】:

    为什么不把事情简单化?

    int times2thenSquared(int x) {
        x = times2(x);
        return squared(x);
    }
    

    (如果你愿意,也可以使用 lambda)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-05
      • 2012-11-27
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      相关资源
      最近更新 更多