为什么其中一个模板静态函数有效,而另一个不起作用
Why does one of these template static functions work, and the other one not?
首先,我的一段代码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) { .... }
无论函数是否为静态函数,这都适用。
相关文章:
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 检查编译时是否存在静态函数
- 名称隐藏对静态函数继承的实例使用
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- 类中静态函数C++意外结果
- 在工人类中使用不同类的静态函数进行实验
- 类 Referention 中C++回调函数引用非静态函数
- 指向模板上下文中的成员函数或静态函数的指针
- 如何检测 Clang AST C++中的静态函数
- 内联asm编译器屏障(内存阻塞器)是算作外部函数,还是算作静态函数调用
- 如何在静态函数中使用成员函数数组
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 生成代码(在编译时)以调用模板的每个实例化的静态函数
- C++无法访问或使用静态函数
- 如何将 cpp 文件中的静态函数公开给其他文件
- 将函数的引用设置为其他 c++ 文件中的非静态函数
- 方法的静态函数的等价性
- 扩展包含静态函数的类
- 非静态函数可以访问静态变量吗?
- 为什么其中一个模板静态函数有效,而另一个不起作用