【问题标题】:Compose lambda function in C++ using parameter pack使用参数包在 C++ 中编写 lambda 函数
【发布时间】:2020-01-31 19:36:42
【问题描述】:

我是 C++ 14 的新手,我想将可变长度的 lambda 函数组合成一个 lambda,我应该怎么做?以下是我目前的工作

#include <iostream>

template<typename Ftype>
Ftype compose(const Ftype & fn) {
  return fn;
}

template<typename Ftype, typename... Other>
auto compose(Ftype fn, Other... other) {
  return [=](auto x){return other(fn(x))...;};
}        ➤ expression contains unexpanded parameter pack 'other'

int main(void) {
  auto add_func = [](const int x) { return x * 7; };
  auto sub_func = [](const int x) { return x + 1; };
  int res = compose(add_func, sub_func)(1);
  std::cout << "Result: " << res << "\n";
}

但是我编译失败了,我想我可能使用了 lambda 或可变参数以某种方式错误。 有人可以帮我吗?

【问题讨论】:

    标签: c++ lambda c++14 variadic-templates function-composition


    【解决方案1】:

    您的“递归”案例不包含对compose 的调用,这应该暗示您在哪里混淆了;)

    return [=](auto x){ return compose(other...)(fn(x)); };
    

    【讨论】:

    • 谢谢!但是我只是尝试了你的方法,它在调用者的 main 中报告错误:表达式不能用作函数 int res = compose(add_func, sub_func)(0); ^ 我应该如何解决这个问题?
    • @user7804610 恐怕这是你的问题,我的这个单一更改makes it work...你使用的是哪个编译器?
    • 非常感谢!!!我在 Makefile 中犯了一个小错误。
    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多