2017-09-25 87 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}}} };' –