lambda表达式在while()中调用,为什么我们需要在lambda表达后添加()

lambda expression is called in the while(),Why do we need to add () after the lambda expression

本文关键字:lambda 添加 while 表达式 调用 为什么 我们      更新时间:2023-10-16
while ([&s]()->bool {
  cout << "Please Input you word<input "q " to exit>:"; 
  return (cin >> s) && (s != "[enter image description here][1]q"); 
}())

lambda表达式是函数定义。调用函数时,必须使用括号,但是当您将函数传递为参数时,只需使用该名称。如果我们将lambda函数存储在称为"条件"的变量中,则可以更好地看到它:

#include <iostream>
#include <string>    
using namespace std;    
int main() {
  string s{};
  auto condition = [&s]() -> bool {
    cout << "Please Input you word:";
    return ((cin >> s) && (s != "enter image description here"));
  };
  while (condition()) {
  }
  return (0);
}

示例:http://cpp.sh/3k6js

参考:http://en.cppreference.com/w/cpp/language/lambda

这也可以写为:

#include <iostream>
#include <string>       
int main() {
  std::string s{};
  while ([&s] {
    std::cout << "Please Input you word:";
    return ((std::cin >> s) && (s != "enter image description here"));
  }()) {
  }
  return (0);
}

示例:http://cpp.sh/7v7gd