指定lambda捕获时出现C++ 11编译错误

Jan*_*gre 2 c++ lambda llvm clang c++11

让这段代码讲述故事(或观看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;
}
Run Code Online (Sandbox Code Playgroud)

我希望能够a在我的lambda中捕获,并能够交替返回值.我的实际情况涉及更多,但归结为此.我希望能够使用lambdas,尽管替代方法是使用带有全局变量的普通函数来保持状态.

我正在编译:

clang++ -std=c++11 testcase.cc
Run Code Online (Sandbox Code Playgroud)

我正在使用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
Run Code Online (Sandbox Code Playgroud)

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

Bry*_*hen 7

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

你应该用 std::function

#include <functional>

int foo(std::function<bool(void)> func) {
  int i; for (i = 0; i < 10 && func(); i++);
  return i;
}
Run Code Online (Sandbox Code Playgroud)

或模板

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