函数重载、函数模板、显式具体化

函数重载

同一函数名接受不同参数来区分

void print(const char * str, int width);
void print(double d, int width);
void print(long l, int width);
void print(int i, int width);
void print(const char * str);
  1. 根据参数(数量、类型、排列顺序)来区分

  2. 不区分double cube(double x)double cube(double &x),因为调用时都是cube(x)

  3. 匹配函数时不区分const和非const变量

    void d(char * bits);           //使用该函数时只接受const参数
    void d(const char * bits);     //使用该函数时接收const参数和非const参数
    
  4. 只能改变参数,不能改变函数类型

    int a(int a);
    double a(double a);       //不能重载:函数类型不相同
    
  5. 仅在函数内容基本相同,但需要接收不同类型的参数时使用函数重载

函数模板

用泛型来传参

template <typename AnyType>          //建立一个模板,将类型命名为AnyType
								  //template <class AnyType>  相同
void swap(AnyType &a, AnyType &b)
{
    AnyType temp;
    temp = a;
    a = b;
    b = temp;
}

重载的模板

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

显式具体化

使模板能够对结构成员进行操作

struct job
{
    char name[40];
    double salary;
};

template <typename T>
void Swap(T &a, T &b)
{
    T temp;
    temp = a;
    a = b;
    b = tmep;
}

template <> void Swap<job>(job &j1, job &j2)
{
    double t1;
    t1 = j1.salary;
    j1.salary = j2.salary;
    j2.salary = t1;
}

int main()
{
    job a = {"Sue",100.5};
    job b = {"Joe",120.23};
    Swap(a,b);					//参数是结构,调用显式具体化函数
    Swap(a.salary,b.salary);	 //参数是结构成员,调用原函数
    cout << "a:" << a.salary << "\tb:" << b.salary << endl;
    Swap(a.salary,b.salary);
    cout << "a:" << a.salary << "\tb:" << b.salary << endl;
}
a:120.23        b:100.5
a:100.5 b:120.23

显式实例化

直接命令编译器创建特定的实例

template void Swap<int>(int, int);

区分实例化template <> void Swap<job>(job &j1, job &j2)与具体化template void Swap<int>(int, int);

完全匹配

从实参到形参
TypeType &
Type &Type
Type []* Type
Type(argument-list)Type (*)(argument=list)
Typeconst Type
Typevolatile Type
Type *const Type
Type *volatile Type *
  • 指向非const数据的指针和引用优先与非const指针和引用参数匹配

  • 非模板函数优先于模板函数(包括显示具体化)

    | const Type |
    | Type * | volatile Type * |

  • 指向非const数据的指针和引用优先与非const指针和引用参数匹配

  • 非模板函数优先于模板函数(包括显示具体化)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值