指定lambda捕获时的c++ 11编译错误

C++11 compilation error when specifying lambda capture

本文关键字:c++ 编译 错误 lambda 指定      更新时间:2023-10-16

让这段代码来讲述这个故事(或者观看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,并能够替换返回值。我实际的案子牵涉到更多,但归结起来就是这个。我希望能够使用lambdas,尽管另一种选择是使用带有全局变量的普通函数来保存状态。

我正在编译:

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

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

可以将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;
}