[英]std::array derived class aggregate initialization
I am making a small helper class that derives from std::array
. 我正在做一个小助手类,该类派生自std::array
。 The constructor does not inherit, obviously, and it is that which is responsible for brace-initialization; 构造函数显然不继承,而是负责括号初始化的对象。 for example: 例如:
template<typename T, size_t size>
struct foo : std::array<T,size>
{
foo(int a, int b)
: std::array<T,size>{a,b}
{
//nothing goes here since constructor is just a dummy that
//forwards all arguments to std::array constructor
}
}
int main()
{
foo<int,2> myobj = {1,2}; //brace initialization calls custom constructor with inner elements as arguments
}
The amount of arguments has to match exactly, so I am leaning towards using something like a variadic function argument in the constructor (since I am not only going to be using 2 elements in the array every single time). 参数的数量必须完全匹配,因此我倾向于在构造函数中使用类似可变参数函数的参数(因为我不仅会每次都在数组中使用2个元素)。 Using this, how would I forward the variadic argument pack to the std::array
constructor? 使用这个,我如何将可变参数包转发到std::array
构造函数? I am open to other methods of brace initialization that allow forwarding to the std::array
constructor. 我愿意接受其他支持初始化的方法,这些方法允许转发到std::array
构造函数。
Note: std::initializer_list
requires runtime initialization, and i am looking for a compile time/constexpr compatible method. 注意: std::initializer_list
需要运行时初始化,我正在寻找兼容编译时/ constexpr的方法。 Thank you. 谢谢。
You can use a perfect-forwarding constructor: 您可以使用完美转发的构造函数:
template<class... U>
foo(U&&... u)
: std::array<T, size>{std::forward<U>(u)...}
{}
I don't think that inheriting from a standard container is a good idea. 我认为从标准容器中继承不是一个好主意。
Anyway... 无论如何...
You can use variadic templates, perfect forwarding and also SFINAE to impose that the number of arguments is exactly size
. 您可以使用可变参数模板,完善的转发功能以及SFINAE来强加参数数量恰好为size
。
You can also make constexpr
the foo
constructor so you can make constexpr foo
objects. 您还可以使constexpr
为foo
构造函数,以便使constexpr foo
对象成为可能。
By example 举个例子
#include <array>
#include <type_traits>
template <typename T, std::size_t S>
struct foo : public std::array<T, S>
{
template <typename ... As,
typename std::enable_if<sizeof...(As) == S>::type * = nullptr>
constexpr foo (As && ... as)
: std::array<T, S>{ { std::forward<As>(as)... } }
{ }
};
int main ()
{
//constexpr foo<int, 2u> myobj1 = {1}; // compilation error
constexpr foo<int, 2u> myobj2 = {1, 2}; // compile
//constexpr foo<int, 2u> myobj3 = {1, 2, 3}; // compilation error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.