template<class T>函数模板
2013-12-21 20:29
441 查看
template<class T>函数模板
2012-03-18 11:28:02| 分类:C++ |字号 订阅
//参考 http://prglab.com/cms/pages/c-tutorial/advanced-concepts/templates.php
函数模板( Function templates)
模板(Templates)使得我们可以生成通用的函数,这些函数能够接受任意数据类型的参数,可返回任意类型的值,而不需要对所有可能的数据类型进行函数重载。这在一定程度上实现了宏(macro)的作用。它们的原型定义可以是下面两种中的任何一个:template <class identifier> function_declaration; template <typename identifier> function_declaration;
上面两种原型定义的不同之处在关键字class 或 typename的使用。它们实际是完全等价的,因为两种表达的意思和执行都一模一样。
例如,要生成一个模板,返回两个对象中较大的一个,我们可以这样写:
template <class GenericType>
GenericType GetMax (GenericType a, GenericType b) { return (a>b?a:b); }
在第一行声明中,我们已经生成了一个通用数据类型的模板,叫做GenericType。因此在其后面的函数中,GenericType 成为一个有效的数据类型,它被用来定义了两个参数a和 b ,并被用作了函数GetMax的返回值类型。
GenericType 仍没有代表任何具体的数据类型;当函数 GetMax 被调用的时候,我们可以使用任何有效的数据类型来调用它。这个数据类型将被作为pattern来代替函数中GenericType 出现的地方。用一个类型pattern来调用一个模板的方法如下:
function <type> (parameters);
例如,要调用GetMax 来比较两个int类型的整数可以这样写:
int x,y; GetMax <int> (x,y);
因此,GetMax 的调用就好像所有的GenericType 出现的地方都用int 来代替一样。
这里是一个例子:
// function template #include <iostream.h> template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax(i,j); n=GetMax(l,m); cout << k << endl; cout << n << endl; return 0; } | 6 10 |
在上面的例子中,我们对同样的函数GetMax()使用了两种参数类型:int 和 long,而只写了一种函数的实现,也就是说我们写了一个函数的模板,用了两种不同的pattern来调用它。
如你所见,在我们的模板函数 GetMax() 里,类型 T 可以被用来声明新的对象
T result;
result 是一个T类型的对象, 就像a 和 b一样,也就是说,它们都是同一类型的,这种类型就是当我们调用模板函数时写在尖括号<> 中的类型。
template <class T> // 最常用的:一个class 参数。
template <class T, class U> // 两个class 参数。
template <class T, int N> // 一个class 和一个整数。
template <class T = char> // 有一个默认值。
template <int Tfunc (int)> // 参数为一个函数。
相关文章推荐
- template<class T>函数模板
- 模板声明中template <typename T>和template <class T>
- UE4 C++类模板 template <class T>
- template<class T>函数模板
- C++中template<class T> && template <typename T>(模板区分)
- template<class T>函数模板
- <C++学习笔记>函数模板 template
- template<class T>
- C++类模板 template <class T>
- c++ 模板<template class T> c++ 模板<template class T>
- c++ error: reference to 'plus' is ambiguous ; template<class _Tp> struct std::plus
- CTypedPtrList<base_class, ele_class>,特定指针类型的模板
- template<class T>(转)
- 关于c++中模板 T 无法限制的替代方案template< T extends Base>
- C++类模板 template <class T>
- template<class T>
- C++类模板 template <class T>
- C++类模板 template <class T>
- 01模板 使用template<class T>
- 模板 使用中注意的问题 template<class T>