为什么有必要在每个函数之前包含模板参数,即使我们在函数中没有使用 diduced 类型

why is it necessary to include template parameter before every function even if we are not using diduced type in the function?

本文关键字:函数 使我们 类型 diduced 包含模 为什么 参数      更新时间:2023-10-16

为什么我们应该在每个函数的前面使用模板参数,即使我们在函数中没有使用推导的模板参数。正如我们所看到的,我没有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();
}