2017-09-25 26 views
0

网络连接有一个矩阵类的一个模板:初始化矩阵类括号,同时类型安全

template<typename T, int rows, int cols> 
struct Matrix{ 
public: 
    Matrix() { 
     if (rows == cols) 
      LoadIdentity(); 
    } 

    T data[rows][cols]; 

    void LoadIdentity(){ } 

    /* more methods ... */ 

} 
template<int rows, int cols> 
using matrixf = Matrix<float, rows, cols>; 
template<int rows, int cols> 
using matrixd = Matrix<double, rows, cols>; 

,我希望能够初始化这个类,如:

void main(){ 
    matrixf<2, 3> m2x3 = { { 1, 2, 3 }, {4, 5, 6} }; 
} 

如果我试试这个,编译器说:

E0289没有构造函数“vian :: Matrix [with T = float,rows = 2,cols = 3]”的实例匹配参数列表

如果我删除我的默认构造函数,我得到我想要的行为,但我失去了任何构造函数的可能性。

Matrix() { ... } // If I remove this, I have the behaviour I want 

一个solution I found是创建一个构造函数的的std :: initializer_list,但如果我这样做,编译器不会检查initialier名单有观点的权利量为N×M大小的矩阵。

编辑:添加LoadIdentity方法,以便编译。

+0

'void main' - >这是C++吗? –

+0

我们这个代码的用例是什么? –

+0

'Matrix(std :: array ,rows>)''? – Jarod42

回答

0

我能做的最好的事情就是实现@ Jarod42的建议。按照他所描述的方式创建构造函数:

Matrix(std::array<std::array<T, cols>, rows>)? -Jodod 42

即使它没有做我想要的。我把它当作答案,因为它比我在(具有std :: initializer_list的构造函数)之前所做的更安全。它可以确保你不会传递比它可能需要更多的参数,但允许你指定更少的参数。 例如

matrixf<2, 3> m2x3{ {1, 2, 3, 4, 5, 6} }; // this compiles. 
matrixf<2, 3> m2x3{ {1, 2, 3, 4} }; // this also compiles. Missing values are automatically set to 0. 

这种方法的缺点是语法。我想通过用大括号来描述每一行来初始化我的矩阵类:

matrixf<2, 3> m2x3{ {1, 2, 3}, {4, 5, 6} }; // this does not compile. 
matrixf<2, 3> m2x3{ { {1, 2, 3}, {4, 5, 6} } }; // this does not compile. 
+0

您错过了一对大括号'matrixf <2, 3> m2x3 {{{{1,2,3},{4,5,6}}} };' –