模板的声明和实现必须放在一起编译
函数模板
函数模板可以重载,由函数模板产生的函数称为模板函数
#include <iostream>
using namespace std;
template <class T1,class T2>
T1 max(T1 a,T2 b){
return a>b?a:b;
}
template <class T,int size>
void show(){
if(size<0)
cout<<"-1";
else
cout<<size<<endl;
}
int main(){
cout<<max<int,int>(1,2)<<endl;
cout<<max(1,2.2)<<endl;
cout<<max(2.2,1)<<endl;
show<int,5>();
}
类模板
由类模板产生的类称为模板类
#include <iostream>
using namespace std;
template <typename T>
class Node{
T x = 0;
T y = 0;
public:
void show();
void display(){
cout<<x<<" "<<y<<endl;
}
};
template<typename T>//according to this format
void Node<T>::show(){
cout<<x<<" "<<y<<endl;
}
int main(){
Node<int> node;
node.show();
node.display();
}
本文深入探讨了函数模板和类模板的使用,展示了如何通过模板实现泛型编程,包括模板函数的重载、模板参数的使用及模板类的实例化。

962

被折叠的 条评论
为什么被折叠?



