gpt4 book ai didi

c++ - 初始化聚合基础(GCC 和 clang 不同意)

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:41 24 4
gpt4 key购买 nike

以下代码可以在 clang 3.6 (C++14) 上编译,但不能在 GCC 5.3 (C++14) 上编译

#include <array>
#include <utility>

struct super: std::array<int, 3> {
using base = std::array<int, 3>;

template <typename... Ts>
super(Ts&&... xs)
: base{std::forward<Ts>(xs)...} {
// nop
}
};

int main() {
super obj(1, 2, 3);
}

产生的错误信息是

/tmp/gcc-explorer-compiler116029-73-105rz4g/example.cpp: In instantiation of 'super::super(Ts&& ...) [with Ts = {int, int, int}]':
15 : required from here
9 : error: array must be initialized with a brace-enclosed initializer
: base{std::forward<Ts>(xs)...} {
^
9 : error: too many initializers for 'std::array<int, 3ul>'

我想我是在用大括号括起来的初始化程序初始化基本聚合。不?标准对此处的语法有何规定?

最佳答案

这当然是允许的;见 [array.overview] ,这保证了 array 的聚合初始化按照您的示例要求的方式工作。你在 GCC 的大括号省略中遇到了一个错误,如果聚合是一个基类,它就不能正常工作:

struct A {int i[1];}; // Equivalent to libstdc++'s std::array<int, 1> implementation
// for this demonstration
struct C : A {
C() : A{0} {}
};

这已在主干中修复:Demo with GCC trunk .

关于c++ - 初始化聚合基础(GCC 和 clang 不同意),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088100/

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