首页 > 解决方案 > while()中调用了lambda表达式,为什么要在lambda表达式后面加()

问题描述

while ([&s]()->bool {
  cout << "Please Input you word<input \"q \" to exit>:"; 
  return (cin >> s) && (s != "[enter image description here][1]q"); 
}())

标签: c++c++11

解决方案


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


推荐阅读