泛型编程,英文叫做Generic programming

可以理解为,具有通用意义的、普适性的,编程。

比如,你要实现一个函数去比较两个数值的大小,数值可能是int或者string。初次尝试,我们直观会想到定义多个重载函数。如下:

int compare(const string &v1, const string &v2)

{

  if( v1 < v2) return -1;

  if ( v2 < v1) return 1;

  return 0;

}

int compare(const int &v1, const int &v2)

{

  if( v1 < v2) return -1;

  if ( v2 < v1) return 1;

  return 0;

}

这两个函数除了参数的类型之外,几乎完全一样。随着比较的类型增多,我们不得不定义很多类似且冗余的函数。

泛型编程就是为了解决此类问题,让我们独立于任何特定的类型来编写代码。

 

模板是c++泛型编程的基础。模板定义以关键字template开始,后面跟一个模板参数列表。模板参数列表用<>包围起来,里面是用逗号分隔的一个或多个模板参数。

例如,上述的需求可以写成如下:

template <typename T>

int compare(const T &v1, const T &v2)

{

  if( v1 < v2) return -1;

  if( v2 < v1) return 1;

  return 0;

}