Lambda没有自动推断出返回类型

ser*_*iol 3 c++ lambda return-type type-deduction

当我在/sf/answers/2248084891/上回答我自己的问题时,我又有了疑问.

const CArray<CItem*>& Items=
    (ItemsInput!= nullptr)?
        *ItemsInput
    :
        [this]() -> const CArray<CItem*>&
        {
            CArray<CItem*> InnerItems;
            GetContainer().GetInnerItems(InnerItems, NULL, true);
            return (InnerItems);
        } ()
;
Run Code Online (Sandbox Code Playgroud)

我试图删除-> const CArray<CItem*>&返回部分,但在编译时它给出了两个错误:

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
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下原因吗?是不是应该让lambda自动推断出从return语句返回的类型?

For*_*veR 6

从C++ 11标准(N3242 5.1.2/4它真的是旧规范)

如果lambda表达式不包含trailing-return-type,则就好像trailing-return-type表示以下类型:

- 如果复合语句是形式

{attribute-specifier-seq opt return expression; }

lvalue-to-rvalue转换(4.1),数组到指针转换(4.2)和函数到指针转换(4.3)之后返回表达式的类型;

- 否则,无效.

因为你的lambda不只是返回表达式,所以return-type是void.

这被认为是C++ 11(DR-985)中的一个缺陷,即使在C++ 11模式下,许多编译器也放宽了对C++ 14的限制(感谢@dyp).