gpt4 book ai didi

c++ - 为什么这些模板静态函数之一有效,而另一个无效?

转载 作者:行者123 更新时间:2023-11-28 00:56:44 24 4
gpt4 key购买 nike

首先,我在 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;
}

据我所知,这两种实现在技术上没有太大区别。主要区别在于 rotationtranslation

相比使用额外的模板参数

然而,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++ - 为什么这些模板静态函数之一有效,而另一个无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10813033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com