嵌套可变参数模板
Nesting variadic template
我有两个使用初始化列表的 classes。一个是 Vector 样式 class,它包含一个值列表。
Vec.h:
template< typename T, int nDimensions = 2 >
class Vec{
private:
std::array< T, nDimensions > elements_;
public:
template <typename... U>
Vec(U... ts) : elements_{ ts... } {}
}
然后使用时:
typedef Vec< int, 2 > Vec2i;
Vec2i twoi = { 1,2 };
Vec2i twoi2 = twoi; //I have copy constructor and other methods finished.
这个 class 可以正常工作,但是当我尝试将这个 class 与我的 class 样式的 Matrix 一起使用时,我无法找出其构造函数的正确语法。
template< typename T, int X,int Y>
class Mat {
private:
std::array< Vec<T, X>, Y > elements_;
}
我喜欢这样使用它:
typedef Mat<int, 3,3> Mat3i;
Mat3i threemat = { {1,2,3},
{4,5,6},
{7,8,9}};
现在,iv 尝试使用初始化列表作为构造函数并取得了一些成功,但我无法弄清楚传递子列表的语法。
Mat(std::initializer_list<Vec<T, X>> values) {
for (auto& t : values) {
//What goes here?
}
}
我也试过迭代列表并手动分配它们,但那是不行的。
还值得注意的是,重要的是这些 classes 具有用于列表的连续内存块,并且没有其他变量。否则 id 将使用其他类型而不是 std::array。 (用于铸造和联合目的。)
我在考虑是否需要将每个值重新解释为 Vec,然后复制这些值。
我是个白痴
Mat(std::initializer_list<Vec<T, X>> values) {
int i = 0;
for (auto& t : values) {
elements_[i++] = t;
}
}
替代方案:
Mat(std::initializer_list<Vec<T, X>> values) {
std::copy(values.begin(), values.end(), elements_.begin());
}
我有两个使用初始化列表的 classes。一个是 Vector 样式 class,它包含一个值列表。
Vec.h:
template< typename T, int nDimensions = 2 >
class Vec{
private:
std::array< T, nDimensions > elements_;
public:
template <typename... U>
Vec(U... ts) : elements_{ ts... } {}
}
然后使用时:
typedef Vec< int, 2 > Vec2i;
Vec2i twoi = { 1,2 };
Vec2i twoi2 = twoi; //I have copy constructor and other methods finished.
这个 class 可以正常工作,但是当我尝试将这个 class 与我的 class 样式的 Matrix 一起使用时,我无法找出其构造函数的正确语法。
template< typename T, int X,int Y>
class Mat {
private:
std::array< Vec<T, X>, Y > elements_;
}
我喜欢这样使用它:
typedef Mat<int, 3,3> Mat3i;
Mat3i threemat = { {1,2,3},
{4,5,6},
{7,8,9}};
现在,iv 尝试使用初始化列表作为构造函数并取得了一些成功,但我无法弄清楚传递子列表的语法。
Mat(std::initializer_list<Vec<T, X>> values) {
for (auto& t : values) {
//What goes here?
}
}
我也试过迭代列表并手动分配它们,但那是不行的。
还值得注意的是,重要的是这些 classes 具有用于列表的连续内存块,并且没有其他变量。否则 id 将使用其他类型而不是 std::array。 (用于铸造和联合目的。)
我在考虑是否需要将每个值重新解释为 Vec,然后复制这些值。
我是个白痴
Mat(std::initializer_list<Vec<T, X>> values) {
int i = 0;
for (auto& t : values) {
elements_[i++] = t;
}
}
替代方案:
Mat(std::initializer_list<Vec<T, X>> values) {
std::copy(values.begin(), values.end(), elements_.begin());
}