【发布时间】:2016-06-15 19:15:43
【问题描述】:
我正在创建一个简单的 C++ 矩阵模板类,其定义如下:
template<uint n, uint m, typename T = double>
class Matrix {
private:
T data[n][m];
static Matrix<n, m, T> I;
public:
Matrix();
Matrix(std::initializer_list<T> l);
T& at(uint i, uint j); // one-based index
T& at_(uint i, uint j); // zero-based index
template<uint k> Matrix<n, k, T> operator*(Matrix<m, k, T>& rhs);
Matrix<m, n, T> transpose();
Matrix<n, m, T> operator+(const Matrix<n, m, T>& rhs);
Matrix<n, m, T>& operator+=(const Matrix<n, m, T>& rhs);
Matrix<n, m, T> operator-(const Matrix<n, m, T>& rhs);
Matrix<n, m, T>& operator-=(const Matrix<n, m, T>& rhs);
Matrix<n, m, T> operator*(const T& rhs);
Matrix<n, m, T>& operator*=(const T& rhs);
Matrix<n, m, T> operator/(const T& rhs);
Matrix<n, m, T>& operator/=(const T& rhs);
static Matrix<n, m, T> identity();
};
(uint 被定义为unsigned int)
最终函数Matrix<n, m, T> identity() 旨在返回静态I 成员,它是使用基本单例模式的单位矩阵。显然,单位矩阵只为方阵定义,所以我尝试了这个:
template<uint n, typename T>
inline Matrix<n, n, T> Matrix<n, n, T>::identity() {
if (!I) {
I = Matrix<n, n, T>();
for (uint i = 0; i < n; ++i) {
I.at(i, i) = 1;
}
}
return I;
}
这给出了错误C2244 'Matrix<n,n,T>::identity': unable to match function definition to an existing declaration。
我的印象是我可以对模板进行某种特殊化,其中列数和行数相等。我不确定这是否可能,但非常感谢您的帮助。
【问题讨论】:
标签: c++ templates matrix static