c++ - 如何使数组的派生类型接受聚合初始化?

标签 c++ c++11 initialization stdarray

例如

class A : public std::array<int, 3>
{
};

A a{1, 2, 3}; // failed currently.

如何让数组的派生类型接受聚合初始化?

最佳答案

您可以提供一个可变模板构造函数,如下所示:

class A : public std::array<int, 3> {
public:
  template<typename... Args> constexpr A(Args&& ...args) 
    : std::array<int, 3>{{std::forward<Args>(args)...}} {}
};

Live Demo

编辑:

以下版本也适用于 Visual Studio:

class A : public std::array<int, 3> {
public:
    template<typename... Args> constexpr A(Args&& ...args) 
      : std::array<int, 3>(std::array<int,3>{std::forward<Args>(args)...}) {}
};

Live Demo

关于c++ - 如何使数组的派生类型接受聚合初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37808553/

相关文章:

c++ - 为什么 _kbhit() 在 C 程序中只工作一次?

android - 寻找一种通用方法来初始化 misc View 对象

c++ - C++中两个堆栈的有效表示?

c++ - 获得std::set中间(中位数)的有效方法?

c++ - 关闭 Eclipse 错误(不是真正的错误)

c++ - ostream 不打印添加两个 valarrays 的结果(使用运算符重载)

c++ - std::unique_ptr 内存和性能

c++ - 从使用异步启动的方法回调的最优雅方式

c# - 使用new时的数组初始化

c - 字符串的声明和初始化