【问题标题】:Does a placeholder in a trailing-return-type override an initial placeholder?尾随返回类型中的占位符是否覆盖初始占位符?
【发布时间】:2014-08-07 05:42:18
【问题描述】:

g++ 似乎接受 autodecltype(auto) 的任意组合作为初始和尾随返回类型:

int a;
auto f() { return (a); }                             // int
auto g() -> auto { return (a); }                     // int
auto h() -> decltype(auto) { return (a); }           // int&
decltype(auto) i() { return (a); }                   // int&
decltype(auto) j() -> auto { return (a); }           // int
decltype(auto) k() -> decltype(auto) { return (a); } // int&

但是,clang 拒绝 jk,说:错误:具有尾随返回类型的函数必须指定返回类型 'auto',而不是 'decltype(auto)' (demonstration )。

哪个编译器是正确的?在每种情况下应使用哪条规则(autodecltype(auto))?在 trailing-return-type 中使用占位符类型是否有意义?

【问题讨论】:

    标签: c++ decltype c++14 trailing-return-type return-type-deduction


    【解决方案1】:

    auto 在引入 trailing-return-type 时是必需的。

    §8.3.5 [dcl.fct] /2

    T D 的声明中,D 的格式为

    D1 ( parameter-declaration-clause ) cv-qualifier-seqoptref-qualifieroptexception-specificationoptattribute-specifier-seqopttrailing-return-type

    声明T D1中包含的declarator-id的类型是“derived-declarator-type-listT”,

    T 应该是单个类型说明符 auto。 [...]

    另请参阅Core Issue 1852,了解与 [dcl.spec.auto]/1 的明显矛盾。

    【讨论】:

    • 您应该将此报告为 GCC 的错误,顺便说一句。
    【解决方案2】:

    @Xeo建设性cmets之后编辑:

    看来这个问题是由于标准草案的两处矛盾造成的。

    根据草案标准§ 7.1.6.4 auto specifier [dcl.spec.auto]:

    1 autodecltype(auto) type-specifiers 指定一个占位符类型,稍后将被替换,可以通过从初始化程序中推导,也可以通过带有尾随-return- 的显式规范类型。自动类型说明符 也用于表示 lambda 是通用 lambda。

    2 占位符类型可以在 decl-specifier-seq、type-specifier-seq、 Conversion-function-id 或 trailing-return-type,在此类声明符有效的任何上下文中。如果函数 声明器包括一个尾随返回类型(8.3.5),它指定函数的声明返回类型。 如果函数声明的返回类型包含占位符类型,则函数的返回类型为 从函数体中的 return 语句推导出来。

    以上的唯一解释表明 Clang 有一个错误。

    然而,core issue 1852 指定上述与 § 8.3.5/2 函数 [dcl.fct] 相矛盾,应予以更改。问题的状态为准备就绪,表明更改已被接受。

    因此,GCC 有一个应该报告的错误。

    【讨论】:

    • 尾随返回类型的语法为auto ... -> T,其中T 可以是占位符类型。开头的auto 是强制性的。
    • @Xeo 阅读引用的第一句话。它说decltype(auto) 也可以替换为trailing-return-type,这是-> T 语法。
    • 请看Core Issue 1852
    • @Xeo 所以你的意思是标准中存在矛盾?
    • 首先,还没有包含这些词的标准。这是一个草稿。是的,存在矛盾,正如 CWG 问题和它“就绪”的事实所表明的那样,这意味着该决议已被接受。
    猜你喜欢
    • 1970-01-01
    • 2011-08-02
    • 2022-08-16
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2016-10-07
    • 2019-01-04
    • 2014-02-17
    相关资源
    最近更新 更多