C/C++教程

【C++】模板的使用

本文主要是介绍【C++】模板的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <iostream>

using namespace std;

struct job
{
    char name[40];
    double salary;
    int floor;
};
void show(job &j);

template <typename T>
void Swap(T &a,T &b);
const int LIM = 8;
void show(int arr[],int n);

template <typename T>
void Swap(T a[],T b[],int n);

template <> void Swap<job>(job &j1,job &j2);

void Swap(int a,int b);

int main()
{

    int i = 10;
    int j = 20;

    cout <<"i,j = " << i << "," << j << "." <<endl;
    Swap(i,j);
    cout <<"After Swap,now i,j = " << "i,j = " << i << "," << j << "." <<endl;

    double x = 24.5;
    double y = 81.7;
    cout << "x,y = " << x << "," << y << "." << endl;
    Swap(x,y);
    cout <<"After Swap,now x,y = " << "x,y = " << x << "," << y << "." <<endl;

    int d1[LIM] = {0,7,0,4,1,7,7,6};
    int d2[LIM] = {0,7,2,0,1,9,6,9};
    cout << "Origianl arrays: " << endl;
    show(d1,LIM);
    show(d2,LIM);
    Swap(d1,d2,LIM);
    cout << "Swapped arrays: " << endl;
    show(d1,LIM);
    show(d2,LIM);


    job Rick = {"Rick",1000,10};
    job Jack = {"Jack",1100,11};
    show(Rick);
    show(Jack);
    Swap(Rick,Jack);
    cout << "After swap: " << endl;
    show(Rick);
    show(Jack);
    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)
{
    T temp;
    for(int i = 0; i < n; i++)
    {
        temp = a[i];
        a[i] = b[i];
        b[i] = temp;
    }
}

//显示具体化模板,只有形参为job结构体,才发挥作用
template <> void Swap<job>(job &j1,job &j2)
{
    double t1;
    double t2;

    t1 = j1.salary;
    j1.salary = j2.salary;
    j2.salary = t1;

    t2 = j1.floor;
    j1.floor = j2.floor;
    j2.floor = t2;

}

void Swap(int a,int b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
    cout << "this is function not template,a=" << a << ",b=" << b << endl;
}
//普通函数优先级高于显示模板,高于普通模板,相同参数,优先匹配普通函数
void show(int arr[],int n)
{
    for(int i=0;i < n;i++)
    {
        cout << arr[i] <<" ";
    }
    cout << endl;
}

void show(job &j)
{
    cout << j.name << ": " << j.salary <<"on floor" << j.floor << endl;
}

 

这篇关于【C++】模板的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!