是否可以这样编码:while(lambda){}

Yue*_*ang 7 c++ lambda c++11

下面的代码编译时没有错误:

std::string lastName, chldName;
while([&]()
{
      return true;
})
{
  //codes...
}   
Run Code Online (Sandbox Code Playgroud)

但是当我尝试这种方式时:

std::string lastName, chldName;
while([&]()
{
      std::cin >>lastName;
      return true;
})
{
  //codes...
}   
Run Code Online (Sandbox Code Playgroud)

编译器抱怨说:

错误:无法将'main():: {(*&lastName)}'从'main()::'转换为'bool'

如何理解这个错误?是否可以这样使用lambda?

For*_*veR 10

你的第一个例子不是你想要的,它相当于while (true),因为lambda将被转换为函数指针,它将被转换为bool(true) - 它应该是

while([&]()
{
   return true;
}())
Run Code Online (Sandbox Code Playgroud)

请注意lambda的调用

你的第二个例子不会在没有lambda调用的情况下编译,因为你试图访问catched-variables,那是禁止从lambda转换为函数指针,可以转换为bool,但它既不会编译(),也不会编译,

如果lambda表达式不包含trailing-return-type,则就好像trailing-return-type表示以下类型:

- 如果compound-statement的格式为{attribute-specifier-seqopt return expression; lvalue-to-rvalue转换(4.1),数组到指针转换(4.2)和函数到指针转换(4.3)之后返回表达式的类型;

- 否则,无效.

在您的情况下,将推断返回类型void,但由于您返回bool,您应该使用trailing-return-type

while([&]() -> bool
{
      std::cin >>lastName;
      return true;
}())
Run Code Online (Sandbox Code Playgroud)


111*_*111 5

没有必要明确表达返回类型,问题是你要求while循环条件lambda函数是否为true,而不是它返回的值.

实际上你需要在循环条件中调用lambda函数.

while([] {
    return true;
 }()) {
 ///....
 }
Run Code Online (Sandbox Code Playgroud)

编辑

第一次编译而第二次编译的原因不是因为第一次编译没有捕获任何内容.该标准允许将其转换为普通函数指针,该指针可以被评估为bool(nullptr为false).

第二个捕获,它阻止编译器将其转换为函数指针,因此不会编译.