什么类型的变量包含 lambda

What type of variable that contain lambda

你能解释一下在这种情况下 L 是哪种类型吗? 换句话说,我可以使用什么类型来代替 auto 关键字?

int main(){
 int x=0;
 auto L = [x] (int y)->bool{
   return x>y;
 };
  return 0; 
}

在这种情况下,C++11 中没有任何东西可以用来代替 auto,这意味着完全相同的类型。这是因为每个 lambda 表达式的类型都是唯一的、未命名的类型。引用 C++11 5.1.2/3:

The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type — called the closure type — whose properties are described below. ...

您可以使用 std::function 而不是 `auto,但您可能不想这样做。

This article更详细的解释:

The basic principle behind auto is that the compiler knows the type … but you either can’t describe it or don’t want to. There is one primary use-case where you cannot name the type – with lambdas.

文章随后说明了如何使用 std::function 代替,但有 运行 的时间惩罚。