模版理解:
模版的作用:代码重用
可以将
template<class 形参名, class 形参名, ...>
理解为 模版的申明,其他不管是函数模版还是类模版都要在申明前加上模版的申明
class/typename : 类似于 int/float/ostream这些数据类型,
申明类型的类型,其形参名就是 该类型的变量。
形参名通常为T、Type
函数模版
template<class 形参名, class 形参名, ...> 返回值 函数名(参数列表)
{
...
};
类模版
//申明
template<class 形参名, class 形参名, ...> class 类名
{
...
};
//定义实现
template<class 形参名, class 形参名, ...> 类名<形参名,形参名,...>::函数名(类型 形参名, 类型 形参名, ...)
{
...
}
友元模版
//申明示例
template<class T> class Demo
{
private:
T val;
public:
template <class M>
friend M operator+(Demo <M>&m, Demo <M>& m2);
};
//定义实现示例
template <class T>
T operator+(Demo <T>&m, Demo <T>& m2)
{
...
}
特点:
- 模版的申明或定义只能在全局,命名空间或类范围内进行
模版可以使用默认值参数
template<class T, class T2=int> class Demo { ... };
模版可以使用非 类 类型(基本数据类型)模版参数,参数没有顺序要求
template<class T, int max=20> class Demo { ... };
- 函数匹配时不能进行类型隐式转换,只有在运算时才能进行隐式转换
函数模版代码示例:
#include <iostream>
using namespace std;
template<class T> T fun_add(T t1, T t2){
return t1 + t2;
}
template<class T> T fun_edc(T t1, T t2){
return t1 - t2;
}
class A{
private:
int id;
public:
A(int id):id(id){}
friend A operator +(A a1, A a2);
friend ostream& operator <<(ostream& out_t, A a);
};
A operator +(A a1, A a2){
return A(a1.id + a2.id);
}
ostream& operator <<(ostream& out_t, A a){
out_t << a.id << endl;
return out_t;
}
int main(int argc, char *argv[])
{
cout << fun_add(1, 2) << endl;
cout << fun_add(1.1, 2.2) << endl;
cout << fun_edc(1.1, 2.2) << endl;
A a1(10);
A a2(20);
cout << fun_add(a1, a2) << endl;
return 0;
}
类模版代码示例
#include <iostream>
using namespace std;
template <typename T>
class A{
public:
T id;
A(T id);
T getId();
};
template <typename T>
A<T>::A(T id_t){
this->id = id_t;
}
template <typename T>
T A<T>::getId(){
return this->id;
}
class Student{
public:
int id;
char name[50];
Student(){
memset(name, 0, 50);
}
Student(int id_t, char *name_t){
this->id = id_t;
memset(name, 0, 50);
strcpy(this->name, name_t);
}
friend ostream& operator <<(ostream& os, Student stu);
Student& operator =(Student stu){
this->id = stu.id;
memset(name, 0, 50);
strcpy(this->name, stu.name);
}
};
ostream& operator <<(ostream& os, Student stu){
os << stu.id << " " << stu.name << endl;
return os;
}
int main(int argc, char *argv[])
{
A<int> a1(1);
cout << a1.getId() << endl;
A<float> a2(1.1);
cout << a2.getId() << endl;
A<bool> a3(true);
cout << a3.getId() << endl;
Student stu(1, "xiaoli");
A<Student> a4(stu);
Student stu2 = a4.getId();
cout << stu2 << endl;
return 0;
}