摘自《c++ Primer Plus》第6版16.4ios
泛型编程最初诞生于C++中,由Alexander Stepanov和David Musser创立。目的是为了实现C++的STL(标准模板库)。其语言支持机制就是模板(Templates)。c++
面向对象编程关注的是数据,而泛型编程关注的是算法。算法
泛型在C++中的主要实现为模板函数和模板类。编程
函数模板是一个独立于类型的函数,能够产生函数的特定类型版本。函数
模板定义以关键字template开始,后接尖括号括住的模板形参表。spa
模板形参能够是表示类型的类型形参(type parameter),也能够是表示常量表达式的非类型形参(nontype parameter)。code
使用函数模板时,编译器会将模板实参绑定到模板形参。编译器将肯定用什么类型代替每一个类型形参,用什么值代替每一个非类型形参,而后产生并编译(称为实例化)该版本的函数。对象
#include <iostream> template <typename T> int compare(const T &v1, const T &v2); using namespace std; int main() { // compiler instantiates int compare(const int&, const int&) cout << compare(1, 0) << endl; // // compiler instantiates int compare(const string&, const string&) string s1 = "hello", s2 = "world"; cout << compare(s1, s2) << endl; return 0; } template <typename T> int compare(const T &v1, const T &v2) { if (v1 < v2) return -1; if (v2 < v1) return 1; return 0; }
1) 函数模板并非真正的函数,它只是C++编译生成具体函数的一个模子。
2) 函数模板自己并不生成函数,实际生成的函数是替换函数模板的那个函数,好比上例中的add(sum1,sum2),
这种替换是编译期就绑定的。
3) 函数模板不是只编译一份知足多重须要,而是为每一种替换它的函数编译一份。
4) 函数模板不容许自动类型转换。
5) 函数模板不能够设置默认模板实参。好比template <typename T=0>不能够。
C++模版函数的语法
template <typename 模版参数列表…>
函数返回类型 函数名(形参列表…)
上面两行能够合并成一行。开发
在定义的类模板中,使用模板形参做为类型或值的占位符,在使用类时再提供具体的类型或值。编译器
与调用函数模板不一样,使用类模板时,必须为模板形参显示指定实参。
#include <iostream> using namespace std; template <class numtype> //定义类模板 class Compare { private : numtype x,y; public : Compare(numtype a,numtype b) {x=a;y=b;} numtype max( ) {return (x>y)?x:y;} numtype min( ) {return (x<y)?x:y;} }; int main( ) { Compare<int > cmp1(3,7); //定义对象cmp1,用于两个整数的比较 cout<<cmp1.max( )<<" is the Maximum of two integer numbers."<<endl; cout<<cmp1.min( )<<" is the Minimum of two integer numbers."<<endl<<endl; Compare<float > cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较 cout<<cmp2.max( )<<" is the Maximum of two float numbers."<<endl; cout<<cmp2.min( )<<" is the Minimum of two float numbers."<<endl<<endl; Compare<char> cmp3('a','A'); //定义对象cmp3,用于两个字符的比较 cout<<cmp3.max( )<<" is the Maximum of two characters."<<endl; cout<<cmp3.min( )<<" is the Minimum of two characters."<<endl; return 0; }
1) 类模板不是真正的类,它只是C++编译器生成具体类的一个模子。
2) 类模板能够设置默认模板实参。
STL(Standard Template Library,标准模板库)是C++对泛型编程思想的实现,最先是惠普实验室开发的。在被引入C++以前该技术就已经存在了很长的一段时间。后来STL成为ANSI/ISO C++标准的一部分。各个 C++厂商也有各自相应的模板库,这些库效率可能很高,但可移植性不必定好。 STL广义上分为三类:algorithm(算法)、container(容器)和iterator(迭代器),几乎全部的代码都采 用了模板类和模板函数的方式,这相比于传统的由函数和类组成的库来讲提供了更好的代码重用机会。