多维数组是否可以从可变模板填充? [英] Can a multidimensional array be filled from variadic template?
本文介绍了多维数组是否可以从可变模板填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有这样的:
template<unsigned int W,unsigned int H>
class Class
{
int data[W][H];
Class(const (&_data)[W][H])
{
for (int x=0;x<W;x++)
for (int y=0;y<H;y++)
data[x][y] = _data[x][y];
}
template<class... args>
Class()
{
/// black magic
}
}
我可以替换黑魔法,所以第二个构造函数将接受W * H ints?
示例:
What could i replace the "black magic", so the second constructor will accept W*H ints? Example:
Class<3,2> class1(1,2,3,4,5,6);
推荐答案
您可以使用 std :: initializer_list 作为构造函数参数,因为你的数组只有 int [] []
。
you could use std::initializer_list as a constructor parameter, since your array only is of type int[][]
.
Class(std::initializer_list<int> il)
{
if(il.size() < W*H)
throw string("Insufficient elements");//if lesser no. of elements are given.
auto it = il.begin();// iterator to the first element of the list.
for(int i =0;i< W;++i)
{
for(int j =0; j < H;++j)
{
data[i][j] = *it++;// increment the iterator
}
}
}
调用网站将如下所示:
Class<3,2> c{1,2,3,4,5,6};
或
Class<3,2> c = {1,2,3,4,5,6};
如果给定更多的元素,则丢弃extras。 initializer_list
可以提供类型安全,如果发现变窄,将为您提供诊断。
if more elements are given then extras are discarded. initializer_list
can give type safety, and will give you a diagnostic if narrowing is found.
这篇关于多维数组是否可以从可变模板填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文