加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:58:48 所属栏目:百科 来源:网络整理
导读:当我在 https://stackoverflow.com/a/32115498/383779回答我自己的问题时,我又有了疑问. 在 const CArrayCItem* Items= (ItemsInput!= nullptr)? *ItemsInput : [this]() - const CArrayCItem* { CArrayCItem* InnerItems; GetContainer().GetInnerItems(Inn
当我在 https://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< 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

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

解决方法

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

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.

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读