为什么我们要在每个函数前面使用模板参数,即使我们没有在函数中使用推导的模板参数。正如我们所看到的,我没有在 printP()
函数(大约 30)中使用模板参数 _T
然后为什么需要在此函数前面包含模板语法。
注意:
这是我的大类的非常简化的版本,它可能看起来很傻,因为它非常小,但是,请考虑使用模板的情况你的类(class)只有几个 [2-3] 函数,但你必须在每个函数前面键入(甚至复制过去)这个冗长的模板语法,但我问为什么??。
有什么办法可以解决这个问题
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
template<typename _T>
class Thing{
int _p;
_T _k;
public:
Thing(int p, _T k):_p(p),_k(k){}
void printK();
void printP();
};
template<typename _T>
void Thing<_T>::printK(){
cout << _k << endl;
}
template<typename _T>
void Thing<_T>::printP(){
cout << _p << endl; // as we can see that i am not using template paramerter "_T"
} // here in this function then why it is required to include template syntax
int main()
{
Thing<int> a(1,2);
a.printK();
a.printP();
}
最佳答案
因为函数 PrintK 是模板类 Thing<_T> 的成员。对于类外的成员函数定义,函数名还包括类名(它所属的类,这里属于Thing),因为Thing是模板,所以函数名需要你提供模板参数(这里是T)。 例如 类外的函数定义需要以下语法 **
返回类型类名::函数名(参数列表)
* 这里的类(Thing)是模板类,所以它的名字也需要类型(比如Thing<_T>)。 我希望你明白我的意思。
关于c++ - 为什么即使我们没有在函数中使用导出类型,也有必要在每个函数之前包含模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27037667/