概述
#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 << "idt" << "gradet" << "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++模板与模板的重载的全部内容,希望文章能够帮你解决C++模板与模板的重载所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复