1、函数模板举例

template <typename Type>

Type fun(Type &x, Type &y, ...)

{

  Type  a = x;

  .....

}

(1)函数重载实现同函数名多类型适配:

#include <iostream>
#include <string>

using namespace std;

void swap(int &a, int &b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

void swap(double &a, double &b)
{
    double tmp = a;
    a = b;
    b = tmp;
}

void swap(string &a, string &b)
{
    string tmp = a;
    a = b;
    b = tmp;
}

int main(int argc, char *argv[])
{
    int x =10;
    int y = 20;

    double m = 3.14;
    double n = 4.56;

    string s = "Morning";
    string t = "Afternoon";

    cout << "交换前: " << endl;
    cout << "x=" << x << "  " << "y=" << y << endl;
    cout << "m=" << m << "  " << "n=" << n << endl;
    cout << "s=" << s<< "  " << "t=" << t << endl;

    swap(x, y);
    swap(m, n);
    swap(s, t);

    cout <<endl <<  "交换后: " << endl;
    cout << "x=" << x << "  " << "y=" << y << endl;
    cout << "m=" << m << "  " << "n=" << n << endl;
    cout << "s=" << s << "  "<< "t=" << t << endl;
}

xuanmiao@linux:~/Test/C++$ ./test46
交换前: 
x=10  y=20
m=3.14  n=4.56
s=Morning  t=Afternoon

交换后: 
x=20  y=10
m=4.56  n=3.14
s=Afternoon  t=Morning

 

(2)函数模板实现同函数名多类型适配:

#include <iostream>
#include <string>

using namespace std;

template <typename Type>
void myswap( Type& a, Type& b)
{
    Type tmp = a;
    a = b;
    b = tmp;
}


int main(int argc, char *argv[])
{
    int x = 10;
    int y = 20;
    
    double f = 3.1415;
    double g = 2.5687;

    string s = "morning";
    string t = "afternoon";


    cout << "交换前: " << "x="<< x <<" "<<"y="<<y<< endl;
    myswap<int>(x, y);
    cout << "交换后: " << "x="<< x <<" "<<"y="<<y<< endl;

    cout << endl <<"交换前: " << "f="<< f <<"  "<<"g="<<g<< endl;
    myswap<double>(f, g);
    cout << "交换后: " << "f="<< f <<"  "<<"g="<<g<< endl;

    cout << endl <<"交换前: " << "s="<< s <<"  "<<"t="<<t<< endl;
    myswap<string>(s, t);
    cout << "交换后: " << "s="<< s <<"  "<<"t="<<t<< endl;


    return 0;
}

xuanmiao@linux:~/Test/C++$ ./test47
交换前: x=10 y=20
交换后: x=20 y=10

交换前: f=3.1415  g=2.5687
交换后: f=2.5687  g=3.1415

交换前: s=morning  t=afternoon
交换后: s=afternoon  t=morning

 

(3) 重载函数模板

#include <iostream>
#include <cstring>

using namespace std;

template <typename Type>
Type min(Type &a, Type &b)
{
    if(a < b)  
        return a;
    else
         return b;
}

const char* min(const char *a, const char* b)
{
    if(strcmp(a, b) < 0)
        return a;
    else
        return b;
}

 int main(int argc, char *argv[])
 {
    cout << "10 和 8 的较小值是:" << min(10, 8) << endl;
    cout << "moring 和 afternoon 的较小值是:" << min("morning", "afternoon") << endl;   

    return 0;
 }
xuanmiao@linux:~/Test/C++$ ./test48
10 和 8 的较小值是:8
moring 和 afternoon 的较小值是:afternoon

上面如果想比较10和8.8时,不能直接调用min(10, 8.8), 而需要调用min<float>(10, 8.8)

 

posted on 2025-05-05 22:20  轩~邈  阅读(14)  评论(0)    收藏  举报