C++ lambda表达式无法编译

bad*_*ash 4 c++ lambda compiler-errors c++11

我正在cin使用lambda表达式尝试在循环索引中使用循环索引的值:

#include<iostream>
using namespace std;

int main(){
  for(int a, ([](int & b){cin>>b;})(a); a < 2; ++a);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这些是我在ubuntu上使用g ++ 4.5编译时的错误:

forLoopAndCinTest.c++: In function ‘int main()’:
forLoopAndCinTest.c++:5:14: error: expected unqualified-id before ‘[’ token
forLoopAndCinTest.c++:5:14: error: expected ‘)’ before ‘[’ token
forLoopAndCinTest.c++:5:34: error: expected primary-expression before ‘)’ token
forLoopAndCinTest.c++:5:34: error: expected ‘;’ before ‘)’ token
forLoopAndCinTest.c++:5:40: error: name lookup of ‘a’ changed for ISO ‘for’ scoping
forLoopAndCinTest.c++:5:40: note: (if you use ‘-fpermissive’ G++ will accept your code)
forLoopAndCinTest.c++:5:50: error: expected ‘;’ before ‘)’ token
Run Code Online (Sandbox Code Playgroud)

如果我使用普通函数而不是lambda,程序编译正常.
使用-fpermissive也没有帮助.
有任何想法吗?

wil*_*ell 5

这不是for外观如何运作.您正在尝试调用编译器希望您声明的lambda int:

for( int a, int2, ...; a < 2; ++a );
Run Code Online (Sandbox Code Playgroud)

现在,

如果我使用普通函数而不是lambda,程序编译正常

是的,但它可能没有做你认为它做的事情.

void f(int& b)
{
    cin >> b;
}

// ...
for( int a, f(a); a < 2; ++a );
Run Code Online (Sandbox Code Playgroud)

这里,循环声明两个int变量,名为af.循环不会f()像您期望的那样调用.

试试这个:

for( int a; cin >> a && a < 2; ++a );
Run Code Online (Sandbox Code Playgroud)