为什么有必要在每个函数之前包含模板参数,即使我们在函数中没有使用 diduced 类型
why is it necessary to include template parameter before every function even if we are not using diduced type in the function?
为什么我们应该在每个函数的前面使用模板参数,即使我们在函数中没有使用推导的模板参数。正如我们所看到的,我没有在printP()
函数中使用模板参数_T
(大约 30 个),那么为什么需要在此函数前面包含模板语法。
NOTE:
这是我的大类的非常简化的版本,它可能看起来很愚蠢,因为它非常小,但是,考虑一种情况,即您只将模板用于类的几个 [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>)。我希望你明白我的意思。
通常最好将模板类的成员和函数限制为依赖于模板参数的成员和函数。非依赖成员和函数可以放在单独的 non=template 类中(有更好的名称吗?例如:
#include <iostream>
using namespace std;
class ThingBase
{
public:
ThingBase(int p)
: _p(p)
{
}
void printP();
protected:
int _p;
};
void ThingBase::printP(){
cout << _p << endl;
}
template<typename _T>
class Thing : public ThingBase {
_T _k;
public:
Thing(int p, _T k)
: ThingBase(p),
_k(k){}
void printK();
};
template<typename _T>
void Thing<_T>::printK(){
cout << _k << endl;
}
int main()
{
Thing<int> a(1,2);
a.printK();
a.printP();
}
相关文章:
- C++定义构造函数使对象成为非 POD
- 延迟函数使打开的框架窗口冻结,直到指定的时间过去
- 具有空构造函数使数组未初始化会使计算速度变慢
- C++参数化构造函数使代码在传递大输入时停止工作
- enable_if is_same constexpr函数使MSVC失败(但在Clang,GCC中效果很好)
- C ++设置与结构,set.find()函数使错误'invalid comparator'
- 我们不能在类的成员函数中使用线程吗?
- 使用friend函数,我们可以覆盖类的私有成员吗
- 不使用模板参数的函数使过多的代码膨胀?
- 我可以禁止某些函数使程序崩溃吗?
- 视觉 C++当我们在基类中使函数成为纯虚拟时,那么在子类中再次使相同的函数虚拟的必要性是什么
- 链表析构函数使C++程序崩溃
- 非平凡的析构函数使类具有非平凡的可构造性
- 创建一个函数使cin只允许数字
- 函数使一个点绕另一个点旋转
- 如何将函数指针(我们不知道参数的函数)声明为类成员?
- 为什么Vector中的Erase和Insert函数使迭代器失效?
- 可以将std::find函数用于我们自己的类
- 如果我们使用参数构造函数,我们是否需要在c++中提供默认构造函数
- Delete_At链表函数使程序崩溃