我有一个像这样定义的矩阵类:
template <typename T, unsigned int N, unsigned int M>
class TMatrixNxM //Rows x columns
{
public:
TMatrixNxM(T = T(0)); //Default constructor
TMatrixNxM(const std::array<std::array<T, M>, N>&); //Construct from array
TMatrixNxM(std::initializer_list<std::initializer_list<T>>); //Initializer
//...
private:
std::array<std::array<T, M>, N> data; //ROW-MAJOR
};
现在,在使用矩阵的代码中我有:
Math::Matrix3x3 b({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
(注意: Matrix3x3 是 TMatrixNxM&lt; float,3,3&gt; 的typedef,并且它位于 Math 命名空间中)
到现在为止,它起作用了,因为我并不总是有那个数组构造函数,只有初始化程序列表一个。但是现在,编译器甚至没有完成编译,崩溃! (我得到“停止工作”弹出窗口,我必须关闭它,我正在使用MS VS Express 2013)
如果我这样做:
Math::Matrix3x3 b = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
然后它工作正常。这就是我假设:
当我这样做的时候,没有歧义,因为你只能这样调用 initializer_list 构造函数。使用第一种方法,编译器可能会感到困惑,因为 array 是一种聚合类型,这意味着初始化以双括号开始,如:{{...}},但是因为我有一个初始化列表初始化列表我必须使用双括号。但是它真的应该是一个问题吗,因为我从来没有真正做过双括号,那些是一个更大的单括号列表中的单括号列表?
这里到底发生了什么,我该如何解决这个问题?
感谢您的时间!
修改
如果我让构造函数通过const指针获取数组,编译器不会崩溃(因为我从来没有真正在构造函数调用中直接输出数组,我有初始化列表):
TMatrixNxM(const std::array<std::array<T, M>, N>*);
然而有人可以解释之前的实际问题,我的假设是对的吗?
这是一个可用于测试的最小可编译(或者,不是)代码:
#include <array>
#include <initializer_list>
template <typename T, unsigned int N, unsigned int M>
class TMatrixNxM //Rows x columns
{
public:
TMatrixNxM(T = T(0));
TMatrixNxM(const std::array<std::array<T, M>, N>&);
TMatrixNxM(std::initializer_list<std::initializer_list<T>>);
private:
std::array<std::array<T, M>, N> data; //ROW-MAJOR
};
template <typename T, unsigned int N, unsigned int M>
TMatrixNxM<T, N, M>::TMatrixNxM(T par_value)
{
std::array<T, M> temp;
temp.fill(par_value);
data.fill(temp);
}
template <typename T, unsigned int N, unsigned int M>
TMatrixNxM<T, N, M>::TMatrixNxM(const std::array<std::array<T, M>, N> &par_values)
{
data = par_values;
}
template <typename T, unsigned int N, unsigned int M>
TMatrixNxM<T, N, M>::TMatrixNxM(std::initializer_list<std::initializer_list<T>> par_values)
{
int i = 0;
for(std::initializer_list<T> row : par_values)
{
int j = 0;
for(T value : row)
{
data[i][j] = value;
++j;
}
++i;
}
}
int main()
{
TMatrixNxM<float, 3, 3> b({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
return 0;
}
如果用数组注释掉构造函数声明/定义,那么它应该编译并执行正常。如前所述,我使用的是MS VS Express 2013中的编译器。
答案 0 :(得分:0)
好吧,看起来它只适用于微软的编译器。我尝试在使用GCC的Linux机器上编译相同的代码,并且编译没有任何问题。它确实正在调用初始化列表构造函数。如果我在变量中创建一个数组并传递它,它也编译得很好,并调用数组构造函数:
std::array<float, 3> a = {{1, 2, 3}};
std::array<std::array<float, 3>, 3> b = {{a, a, a}};
TMatrixNxM<float, 3, 3> mat(b);
如果我直接初始化数组,它还会编译并调用数组构造函数:
TMatrixNxM<float, 3, 3> mat({{ {{1, 2, 3}}, {{4, 5, 6}}, {{7, 8, 9}} }});