[英]How to make an array's derived type accept aggregate initialization?
For example 例如
class A : public std::array<int, 3>
{
};
And 和
A a{1, 2, 3}; // failed currently.
How to make an array's derived type accept aggregate initialization? 如何使数组的派生类型接受聚合初始化?
You could provide a variadic template constructor as follows: 您可以提供如下的可变参数模板构造函数:
class A : public std::array<int, 3> {
public:
template<typename... Args> constexpr A(Args&& ...args)
: std::array<int, 3>{{std::forward<Args>(args)...}} {}
};
Edit: 编辑:
The following version works also on Visual Studio: 以下版本也适用于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)...}) {}
};
EDIT: As others pointed out in comments, this won't work for std::array
because std::array
doesn't contain constructor taking initializer_list
. 编辑:正如其他人在评论中指出的那样,这对std::array
不起作用,因为std::array
不包含构造函数采用initializer_list
。 But it might be useful for other containers that have constructor taking initializer_list
, for example std::vector
. 但是对于具有构造函数的initializer_list
其他容器,它可能很有用,例如std::vector
。
You can use inheriting constructor (since C++11): 您可以使用继承构造函数 (从C ++ 11开始):
class A: public std::vector<int,3>
{
using std::vector<int,3>::vector;
};
Just define a constructor like that: 只需定义一个这样的构造函数:
A(std::array<int, 3>);
example: 例:
#include <array>
#include <iostream>
struct A : public std::array<int, 3>
{
A(std::array<int, 3> a) :
std::array<int, 3>{a}
{
}
};
int main(void)
{
A a({1, 2, 3});
std::cout << a[0] << "\n";
std::cout << a[1] << "\n";
std::cout << a[2] << "\n";
}
That is not an aggregate initialization, but it is an "as if"... 这不是聚合初始化,但它是“好像”......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.