为什么其中一个模板静态函数有效,而另一个不起作用

Why does one of these template static functions work, and the other one not?

本文关键字:有效 静态函数 不起作用 另一个 一个 为什么      更新时间:2023-10-16

首先,我的一段代码matrix.hpp

template <class T>
class matrix
{
  public:
    matrix();
    T& operator() (size_t i, size_t j) {return elem[i+j*4];}
    const T& operator() (size_t i, size_t j) const {return elem[i+j*4];}
    // ...
    static matrix<T> identity() {return matrix<T>();}
    static matrix<T> translation(const vector<T>&);
    template <class RT> static matrix<T> rotation_x(RT);
    // ...
};
// ...
template <class T>
inline
matrix<T>
matrix<T>::translation(const vector<T>& v)
{
    matrix<T> result;
    result(0, 3) = v.x;
    result(1, 3) = v.y;
    result(2, 3) = v.z;
    return result;
}
template <class T, class RT>
inline
matrix<T>
matrix<T>::rotation_x(RT angle)
{
    RT ca = std::cos(angle);
    RT sa = std::sin(angle);
    matrix<T> result;
    result(1, 1) = +ca;
    result(1, 2) = -sa;
    result(2, 1) = +sa;
    result(2, 2) = +ca;
    return result;
}

据我所知,这两种实现在技术上没有太大区别。主要区别在于,与translation相比,rotation使用额外的模板参数

然而,g++ 不接受我目前拥有rotation的方式:

la/matrix.hpp:272:31: error: invalid use of incomplete type 'class la::matrix<T>'
la/matrix.hpp:16:7: error: declaration of 'class la::matrix<T>'

这是怎么回事?

你的类只有一个模板参数,第二个引用模板类的模板函数,所以你需要

template <class T>
template <class RT>
inline
matrix<T> matrix<T>::rotation_x(RT angle) { .... }

无论函数是否为静态函数,这都适用。