C++模板——泛型编程简介

本文参照于狄泰软件学院——《C++深度剖析课程》

泛型指的是泛指的数据类型。也就是没有特定的类型,也不依赖于具体的数据类型。通常,我们编写函数的返回值,函数参数都需要依赖于具体的数据类型。如果不同类型参数实现相同功能的函数,我们就需要对函数进行重载,重新编写。
但是使用泛型编程,我们就不需要依赖于具体的数据类型了。而在C++中,泛型编程依赖于模板技术。

问题:C++中有什么方法解决依赖类型的方法?

示例代码:宏定义的方式实现泛型编程

#include <iostream>
#include <string>

using namespace std;

#define SWAP(t, a, b)    \
do                       \
{                        \
    t c = a;             \
    a = b;               \
    b = c;               \
}while(0)

int main()
{
    int a = 5, b = 3;
    SWAP(int, a, b);
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    string s1 = "Delphi";
    string s2 = "Shaw";
    SWAP(string, s1, s2);

    cout << "s1 = " << s1 << endl;
    cout << "s2 = " << s2 << endl;

    return 0;
}

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

问题:有什么更好的方法解决类型检查的问题吗?

C++中的泛型编程

函数模板

  1. 一种特殊的函数可用不同类型进行调用
  2. 看起来和普通函数很相似,区别是类型可被参数化

函数模板的语法规则

  1. template关键字用于声明开始进行泛型编程
  2. typename关键字用于声明泛型类型。

函数模板的使用方式

1. 自动类型推导调用
不指定特定类型,让编译器根据我们传入参数来推导出我们所使用的类型。能够根据实参对参数类型进行推导

2. 具体类型显式调用
显式指定参数类型,如:function()

  1. 函数模板是泛型编程在C++中应用方式之一
  2. 函数模板是C++中重要的代码复用方式

示例代码:函数模板使用

#include <iostream>
#include <string>

using namespace std;

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

int main()
{
    int a = 5, b = 3;
    Swap<int>(a, b);
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    string s1 = "Shaw";
    string s2 = "Ousr";
    Swap(s1, s2);
    cout << "s1 = " << s1 << endl;
    cout << "s2 = " << s2 << endl;

    return 0;
}

输出结果:
a = 3
b = 5
s1 = Ousr
s2 = Shaw

猜你喜欢

转载自blog.csdn.net/small_prince_/article/details/80533079