#include <iostream>
#include <string>
template <typename T>
void Swap(T &, T &);
template <typename T>
void Swap(T[], T[], int);
void show (int *, int n);
struct student;
template <> void Swap<student>(student &s1, student &s2);
void showstu(const student &);
//模板函数只是给出了一个生成函数定义的方案,并没有定义函数,函数的定义是由编译器完成的
//对于一个函数名,可以有如下几个版本
//非模板函数
//模板函数
//模板的函数的显示具体化
//以上三个的重载版本
//调用优先级非模板函数 > 显示具体化模板函数 > 模板函数
//根据传入参数类型的不同,生成相应的版本,这个过程叫做实例化
//显示具体化和隐式具体化统称为实例化
struct student
{
int id;
double grade;
std::string name;
};
int main()
{
using namespace std;
int a,b;
double x,y;
string p,t;
cout << "please input a(int) and b(int)";
cin >> a >> b;
cout << "now a is " << a << " b is " << b <<endl;
Swap(a,b);
cout << "function Swap after " << "a is " << a << " b is " << b <<endl;
cout << "please input x(double) and y(double)";
cin >> x >> y;
cout << "now x is " << x << "y is " << y <<endl;
Swap(x,y);
cout << "function Swap after " << "x is " << x << " y is " << y <<endl;
cout << "please input p(string) and t(string)";
cin >> p >>t;
cout << "now p is " << p << "t is " << t;
Swap(p,t);
cout << "function Swap after " << "p is " << p << " t is " << t;
cout << "\n模板类重载" <<endl;
int num1[] {1,2,3,4,5};
int num2[] {5,4,3,2,1};
show(num1, 5);
cout << endl;
show(num2, 5);
cout << "Swap after " <<endl;
Swap(num1,num2,5);
show(num1,5);
cout << endl;
show(num2,5);
cout << "\n具体化 " <<endl;
student s1{20215014,91.5,"wang"},
s2{20215066,96.4,"zhang"};
showstu(s1);
showstu(s2);
Swap(s1,s2);
showstu(s1);
showstu(s2);
return 0;
}
template <typename T>
void Swap(T &a,T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
template <typename T>
void Swap(T a[], T b[],int n)
{
int temp;
for(int i=0;i<n;i++){
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
void show(int *a, int n)
{
for(int i=0;i<n;i++){
std::cout << a[i] << " ";
}
}
void showstu(const student &s)
{
std::cout << "id\t" << "grade\t" << "name" <<std::endl;
std::cout << s.id << "\t" << s.grade << "\t" << s.name << std::endl;
}
//具体化的声明需要<type_name>但是模板函数的实现可以不用
template <> void Swap(student &s1, student &s2)
{
double t1;
int t2;
t1 = s1.grade;
s1.grade = s2.grade;
s2.grade = t1;
t2 = s1.id;
s1.id = s2.id;
s2.id = t2;
}
C++模板与模板的重载
最新推荐文章于 2023-12-25 22:13:20 发布