当用“自动”方法推导时,λ的类型是什么,在C ++ 11? [英] What is the type of lambda when deduced with "auto" in C++11?
问题描述
我有一个感觉,lambda的类型是一个函数指针。当我执行以下测试时,发现它是错误的(演示)。
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
关键字推导时, typeof
是一个lambda表达式吗?
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被直接翻译成函子。 []
中的任何内容都转换为构造函数参数和函子对象的成员,()
中的参数转换为函数运算符()
的参数。
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.
这篇关于当用“自动”方法推导时,λ的类型是什么,在C ++ 11?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!