Lambda没有自动推导返回类型 [英] Lambda did not automatically deduce return type
问题描述
当我在 http://stackoverflow.com/a/32115498/383779 上回答我自己的问题时,我得到了另一个疑问。
在
const CArray< CItem *> & Items =
(ItemsInput!= nullptr)?
* ItemsInput
:
[this]() - > const CArray< CItem *>
{
CArray< CItem *> InnerItems;
GetContainer()。GetInnerItems(InnerItems,NULL,true);
return(InnerItems);
}()
;
我试图删除 - > const CArray< C1tem *>&
返回部分,但在编译时给出了两个错误:
1> FunctionClass.cpp(最后一个分号行):错误C2440:'initializing':无法从'void'转换为'const CArray< TYPE& &'
1> with
1> [
1> TYPE = CItem *
1> ]
1> void类型的表达式不能转换为其他类型
1> FunctionClass.cpp(return语句的行):error C3499:指定为具有void返回类型的lambda不能返回值
有人可以解释为什么吗?不是为lambda自动推导从返回语句返回的类型?
从C ++ 11标准(N3242 5.1.2 / 4它真的旧规范)
如果lambda表达式不包含尾随return-type,它是
,如果trailing-return-type表示以下类型:
- 如果
-statement的形式是
{attribute-specifier-seq opt return expression; }
后返回的表达式的类型l值到值的转换(4.1),数组到指针的转换
(4.2) ,和函数到指针的转换(4.3);
- 否则为空。
因为你的lambda不只是返回表达式,返回类型是void。
这被认为是C + +11( DR-985 )和许多编译器已经放宽了这些限制到C ++ 14即使在C ++ 11模式(感谢@dyp)。
When I answewred my own question on http://stackoverflow.com/a/32115498/383779 , I got another doubt.
In
const CArray<CItem*>& Items=
(ItemsInput!= nullptr)?
*ItemsInput
:
[this]() -> const CArray<CItem*>&
{
CArray<CItem*> InnerItems;
GetContainer().GetInnerItems(InnerItems, NULL, true);
return (InnerItems);
} ()
;
I tried to remove the -> const CArray<CItem*>&
return part, but it gave two errors when compiling:
1>FunctionClass.cpp(line of last semicolon): error C2440: 'initializing' : cannot convert from 'void' to 'const CArray<TYPE> &'
1> with
1> [
1> TYPE=CItem *
1> ]
1> Expressions of type void cannot be converted to other types
1>FunctionClass.cpp(line of the return statement): error C3499: a lambda that has been specified to have a void return type cannot return a value
Can somebody explain why? Wasn't is supposed for the lambda to automatically deduce the type to be returned from its return statement?
From C++11 standard (N3242 5.1.2/4 it's really old specification)
If a lambda-expression does not include a trailing-return-type, it is as if the trailing-return-type denotes the following type:
— if the compound-statement is of the form
{ attribute-specifier-seq opt return expression ; }
the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3);
— otherwise, void.
since your lambda is not just return expression, return-type is void.
This is considered a defect in C++11 (DR-985) and many compilers have relaxed those restrictions to the C++14 even in C++11 mode (thanks @dyp).
这篇关于Lambda没有自动推导返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!