函数模板( Function templates)
模板(Templates)使得我们可以生成通用的函数,这些函数能够接受任意数据类型的参数,可返回任意类型的值,而不需要对所有可能的数据类型进行函数重载。这在一定程度上实现了宏(macro)的作用。它们的原型定义可以是下面两种中的任何一个:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
上面两种原型定义的不同之处在关键字class 或 typename的使用。它们实际是完全等价的,因为两种表达的意思和执行都一模一样。
单参数类型的函数模板:
#include <iostream>
using namespace std;
template <class T> T GetMax(T a, T b){
return (a>b?a:b);
}
int main(int argc, char *argv[]) {
int i = 10, j = 20;
cout << GetMax(i,j) << endl;
}
多参数类型的模板:
#include <iostream>
using namespace std;
template <class T, class U> T GetMax(T a, U b){
return (a>b?a:b);
}
int main(int argc, char *argv[]) {
int i = 100;
long j = 20;
cout << GetMax(i,j) << endl;
}
类模板(Class templates)
使得一个类可以有基于通用类型的成员,而不需要在类生成的时候定义具体的数据类型,例如:
#include <iostream>
using namespace std;
template <class T>
class People {
public:
T name ;
T age;
public:
People(T first, T second){
name = first;
age = second;
}
};
int main(int argc, char *argv[]) {
People<int>p(10, 20);
cout << p.name << endl;
cout << p.age << endl;
}
上面我们定义的类可以用来存储两个任意类型的元素。例如,如果我们想要定义该类的一个对象,用来存储两个整型数据115 和 36 ,我们可以这样写:
pair<int>p (115, 36);
我们同时可以用这个类来生成另一个对象用来存储任何其他类型数据,例如:
pair<float>p (3.0, 2.18);
上面的例子中,类的唯一一个成员函数已经被inline 定义。如果我们要在类之外定义它的一个成员函数,我们必须在每一函数前面加template <... >。
例如:
template <> class class_name <type>