【问题标题】:C++11 compilation error when specifying lambda capture [duplicate]指定 lambda 捕获时的 C++11 编译错误 [重复]
【发布时间】:2014-07-09 13:52:25
【问题描述】:

让这段代码讲述故事(或观看showterm):

#include <iostream>

int foo(bool func (void)) {
  int i; for (i = 0; i < 10 && func(); i++);
  return i;
}

int main() {
  std::cout << foo([] {
    return true;
  }) << std::endl;

  bool a = false;
  std::cout << foo([&a] { // error: no matching function for call to 'foo'
    return a = !a;
  }) << std::endl;

  return 0;
}

我希望能够在我的 lambda 中捕获 a,并能够交替返回值。 我的实际案例涉及更多,但归结为这一点。我希望能够使用 lambda,尽管替代方法是使用带有全局变量的普通函数来保存状态。

我正在编译:

clang++ -std=c++11 testcase.cc

我正在使用 Apple 的 LLVM:

Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.1.0
Thread model: posix

这是一个错误,还是我做错了什么?

【问题讨论】:

    标签: c++ c++11 lambda clang llvm


    【解决方案1】:

    当且仅当它不捕获任何内容时,您可以将 lambda 转换为函数指针 (bool func (void))。所以第一部分可以编译,但第二部分不会。

    你应该使用std::function

    #include <functional>
    
    int foo(std::function<bool(void)> func) {
      int i; for (i = 0; i < 10 && func(); i++);
      return i;
    }
    

    或模板

    template <class TFunc>
    int foo(TFunc && func) {
      int i; for (i = 0; i < 10 && func(); i++);
      return i;
    }
    

    【讨论】:

    • 就是这样。我不知道我怎么找不到原来的问题。
    • 您会希望通过值、“通用引用”或 const 引用来获取 func;对 lambda 表达式求值的结果是纯右值,所以 TFunc &amp; 不起作用。
    • @StuartOlsen 谢谢。已更新。
    猜你喜欢
    • 2014-10-22
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多