我正在创建一个简单的 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
.
我的印象是我可以对列数和行数相等的模板进行某种专门化。我不确定这是否可行,但非常感谢您的帮助。
最佳答案
试试这个:
static Matrix<n, m> identity() {
static_assert(n == m, "Only square matrices have a identity");
return {}; //TODO
}
关于C++模板矩阵类——方阵特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37843972/