C++模板与模板的重载

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值