gpt4 book ai didi

c++ - 结构化绑定(bind)初始化程序表单 { assignment-expression } 在 clang 上的数组类型失败

转载 作者:行者123 更新时间:2023-12-01 14:52:32 26 4
gpt4 key购买 nike

[dcl.dcl]/1 (最终 C++17 草案,N4659)将简单声明的语法描述为:

[...]

simple-declaration: - [...] - attribute-specifier-seq(opt) decl-specifier-seq ref-qualifier(opt) [ identifier-list ] initializer;



[dcl.dcl]/8描述了简单声明的后一种形式是结构化绑定(bind)声明:

A simple-declaration with an identifier-list is called a structured binding declaration ([dcl.struct.bind]). The decl-specifier-seq shall contain only the type-specifier auto and cv-qualifier:s. The initializer shall be of the form “= assignment-expression”, of the form “{ assignment-expression }”, or of the form “( assignment-expression )”, where the assignment-expression is of array or non-union class type.



即,就这个问题而言,结构化绑定(bind)具有简化的语法:

auto [ identifier-list ] initializer ;



以下任何形式都是有效的初始化程序:s:

... = assignment-expression

... { assignment-expression }

... ( assignment-expression )



因此,可以说以下代码格式正确:
struct S { int s; };

int main() {
const S s{42};
const int arr[1] = {42};

// ... of the form “= assignment-expression”
auto[s_form1] = s;
auto[e_form1] = arr;

// ... of the form “{ assignment-expression }”
auto[s_form2]{s};
auto[e_form2]{arr};

// ... of the form “( assignment-expression )”
auto[s_form3](s);
auto[e_form3](arr);

(void)s_form1; (void)s_form2; (void)s_form3;
(void)e_form1; (void)e_form2; (void)e_form3;

return 0;
}

同时使用 -std=c++17-std=c++2a , GCC (9.3) 接受此代码,而 clang (10.0.0 以及 HEAD/11) 拒绝数组的“{ assignment-expression }”形式:

auto[e_form2]{arr};
^~~
error: cannot initialize an array element of type 'const int'
with an lvalue of type 'const int [1]'


对于右值数组,它同样失败:

using SingleElementIntArray = int[1];
auto[e_form2]{SingleElementIntArray{42}};
^~~~~~~~~~~~~~~~~~~~~~~~~
error: cannot initialize an array element of type
'int' with an rvalue of type
'SingleElementIntArray' (aka 'int [1]')


问题
  • 谁在这里,GCC 还是 clang?我的猜测是 GCC;如果是这样,这是一个已知的clang错误吗?
  • 最佳答案

    这是一个已知的错误,有一个开放的错误报告

    LLVM 打开错误报告:

  • Bug 32466 - Clang doesn't support structured binding of initializer form {" expr }" for array

  • Ryou Ezoe 2017-03-30 00:24:07 PDT:

    Clang doesn't support structured binding of initializer form {" expr }" if expr is id-expression of array object. Clang does not accept following code.

    int expr[] = { 1,2,3 } ;
    auto [a,b,c]{expr} ;

    with the error:

    prog.cc:4:18: error: cannot initialize an array element of type 'int' with an lvalue of type 'int [3]'



    其他情况按预期工作。 "( expr )"和 "{
    expr }"其中 expr 是类对象的 id 表达式:
    auto [a,b,c](expr) ;

    struct X { int x,y,z } ;
    X x {1,2,3} ;
    auto [a,b,c]{ x } ;

    关于c++ - 结构化绑定(bind)初始化程序表单 { assignment-expression } 在 clang 上的数组类型失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62198799/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com