C++模板矩阵类——方阵特化

标签 c++ templates matrix static

我正在创建一个简单的 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
}

参见:http://cpp.sh/7te2z

关于C++模板矩阵类——方阵特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37843972/

相关文章:

c++ - 如何捕获初始化列表中的异常?

c++ - 静态库中的符号有时会链接到可执行文件中,有时不会

c++ - "::functionName()"在 C++ 中意味着什么?

javascript - 如何在 Javascript 中获取 Sitecore 6 模板名称或 ID?

r - 如何在 R 中将一个矩阵的 upper.tri 与另一个矩阵的 lower.tri 结合起来?

matlab - 向矩阵中添加一行

c# - 打印出矩阵及其转置,C#

c++ - 如何使用getaddrinfo()?

c++ - 两个几乎相同的调用,一个有效,一个失败

C++ 多态性 : what am I missing?