函数模板概念

为什么要有函数模板?

需求:写n个函数,交换char类型、int类型、double类型变量的值。

案例:

#include <iostream>
using namespace std;
/*
void myswap(int &a, int &b)
{
    int t = a;
    a = b;
    b = t;
}

void myswap(char &a, char &b)
{
    char t = a;
    a = b;
    b = t;
}
*/

//template 关键字告诉C++编译器 我要开始泛型了.你不要随便报错  
//数据类型T 参数化数据类型
template <typename T>
void myswap(T &a, T &b)
{
    T t;
    t = a;
    a = b;
    b = t;
}

void main()
{
    //char a = 'c';
    
    int  x = 1;
    int     y = 2;
    myswap(x, y); //自动数据类型 推导的方式 

    float a = 2.0;
    float b = 3.0;

    myswap(a, b); //自动数据类型 推导的方式 
    myswap<float>(a, b); //显示类型调用 

    cout<<"hello..."<<endl;
    system("pause");
    return ;
}

函数模板语法

函数模板定义形式

template    < 类型形式参数表 >   

类型形式参数的形式为:

                     typename T1 typename T2 , …… , typename Tn

      或     class T1 class T2 , …… , class Tn  

函数模板调用

                   myswap<float>(a, b);       //显示类型调用

                  myswap(a, b);                   //自动数据类型推导

原文地址:https://www.cnblogs.com/gd-luojialin/p/9750159.html