问题描述
我有一种看法,即 lambda 的类型是一个函数指针.当我执行以下测试时,我发现它是错误的(demo).
I had a perception that, type of a lambda is a function pointer. When I performed following test, I found it to be wrong (demo).
#define LAMBDA [] (int i) -> long { return 0; }
int main ()
{
long (*pFptr)(int) = LAMBDA; // ok
auto pAuto = LAMBDA; // ok
assert(typeid(pFptr) == typeid(pAuto)); // assertion fails !
}
上面的代码是否遗漏了任何一点?如果不是,那么用 auto
关键字推导出 lambda 表达式时 typeof
是什么?
Is above code missing any point ? If not then, what is the typeof
a lambda expression when deduced with auto
keyword ?
推荐答案
未指定 lambda 表达式的类型.
The type of a lambda expression is unspecified.
但它们通常只是函子的语法糖.一个 lambda 被直接翻译成一个函子.[]
里面的任何东西都变成了构造函数参数和函子对象的成员,而 ()
里面的参数变成了函子的 operator() 的参数
.
But they are generally mere syntactic sugar for functors. A lambda is translated directly into a functor. Anything inside the []
are turned into constructor parameters and members of the functor object, and the parameters inside ()
are turned into parameters for the functor's operator()
.
不捕获任何变量的 lambda([]
中没有任何内容)可以转换为函数指针(MSVC2010 不支持此功能,如果这是您的编译器,但这种转换是标准的一部分).
A lambda which captures no variables (nothing inside the []
's) can be converted into a function pointer (MSVC2010 doesn't support this, if that's your compiler, but this conversion is part of the standard).
但是 lambda 的实际类型不是函数指针.这是某种未指定的函子类型.
But the actual type of the lambda isn't a function pointer. It's some unspecified functor type.
这篇关于用“auto"推导出 lambda 的类型是什么?在 C++11 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!