56、函数模板的概念和意义

c++中有几种交换变量的方法:

定义宏代码块  vs  定义函数

#include <iostream>
#include <string>
using namespace std;

#define SWAP(t, a, b)    \           //多行定义宏

do                         \
{                           \
    t c = a;             \
    a = b;               \
    b = c;               \

}while(0)

void Swap(int& a, int& b)
{
    int c = a;
    a = b;
    b = c;
}
void Swap(double& a, double& b)
{
    double c = a;
    a = b;
    b = c;
}
void Swap(string& a, string& b)
{
    string c = a;
    a = b;
    b = c;
}
int main()
{
    int a = 0;
    int b = 1; 
    Swap(a, b);    
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;    
    double m = 2;
    double n = 3;    
    Swap(m, n);   
    cout << "m = " << m << endl;
    cout << "n = " << n << endl;    
    string d = "Delphi";
    string t = "Tang";    
    Swap(d, t);    
    cout << "d = " << d << endl;
    cout << "t = " << t << endl;    
    return 0;
}

定义宏代码块:优点:代码复用,适合所有的类型,缺点:编译器不知道宏的存在,缺少类型检查。

定义函数:优点:真正的函数调用,编译器对类型进行检查。缺点:根据类型重复定义函数,无法代码复用。

泛型编程的概念:不考虑具体数据类型的编程方式,对于swap函数可以用泛型写法,

void swap(T&a,T& b)

{

T t=a;

a=b;

b=t;

}

C++中的泛型编程:函数模板:一种特殊的函数可用不同类型进行调用,看起来和普通函数相似,区别是类型可被参数化,

语法规则:template关键字用于声明开始进行泛型编程。typename关键字用于声明泛型类型。

函数模板的使用:自动类型推导调用,具体类型显示调用

int a=0;

int b=1;

swap(a,b); //自动推导

float c=2;

float d=3;

swap<float>(c,d);//显示调用

#include <iostream>
#include <string>
using namespace std;
template < typename T >
void Swap(T& a, T& b)
{
    T c = a;
    a = b;
    b = c;
}
template < typename T >
void Sort(T a[], int len)         //排序数组
{
    for(int i=0; i<len; i++)
    {
        for(int j=i; j<len; j++)
        {
            if( a[i] > a[j] )
            {
                Swap(a[i], a[j]);
            }
        }
    }
}
template < typename T >
void Println(T a[], int len)       //打印数组元素值
{
    for(int i=0; i<len; i++)
    {
        cout << a[i] << ", ";
    }    
    cout << endl;
}
int main()

{

//swap(a,b);  //==swap<int>(a,b);

    int a[5] = {5, 3, 2, 4, 1};    
    Println(a, 5);
    Sort(a, 5);
    Println(a, 5);    
    string s[5] = {"Java", "C++", "Pascal", "Ruby", "Basic"};    
    Println(s, 5);
    Sort(s, 5);
    Println(s, 5);    
    return 0;
}
函数模板是泛型编程在c++中的应用方式之一,函数模板能够根据实参对参数类型进行推导,函数模板支持显示的指定参数类型。函数模板是c++中重要的代码复用方式。

猜你喜欢

转载自blog.csdn.net/ws857707645/article/details/80269190