Sas*_*hra 1 c++ templates aggregate-initialization variadic-templates c++11
我正在制作一个源自的小助手类std::array.显然,构造函数不会继承,而是负责大括号初始化的构造函数; 例如:
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
}
Run Code Online (Sandbox Code Playgroud)
参数的数量必须完全匹配,所以我倾向于在构造函数中使用类似variadic函数的参数(因为我不仅每次都在数组中使用2个元素).使用这个,我如何将可变参数包转发给std::array构造函数?我对其他支持初始化方法持开放态度,允许转发给std::array构造函数.
注意:std::initializer_list需要运行时初始化,我正在寻找编译时/ constexpr兼容方法.谢谢.
您可以使用完美转发构造函数:
template<class... U>
foo(U&&... u)
: std::array<T, size>{std::forward<U>(u)...}
{}
Run Code Online (Sandbox Code Playgroud)