C++中的template

来源:互联网 发布:畅游无限制浏览器 mac 编辑:程序博客网 时间:2024/06/07 00:17

一、.函数模板(function templates)

 函数模板声明格式:

template <class identifier> function_declaration;template <typename identifier> function_declaration;

如:

template <class myType>myType GetMax (myType a, myType b) { return (a>b?a:b);}

调用形式:

function_name <type> (parameters);

如:

int x,y;GetMax <int> (x,y);

实例:

// function template#include "stdafx.h"#include <iostream>using namespace std;template <class T>T GetMax (T a, T b) {T result;result = (a>b)? a : b;return (result);}int _tmain(int argc, _TCHAR* argv[]){int i=5, j=6, k;long l=10, m=5, n;k=GetMax<int>(i,j);n=GetMax<long>(l,m);cout << k << endl;cout << n << endl;return 0;}

二、类模板(class template)

形式如下:

template <class T>class mypair {    T values [2];  public:    mypair (T first, T second)    {      values[0]=first; values[1]=second;    }};

调用形式如:

mypair<int> myobject (115, 36);
mypair<double> myfloats (3.0, 2.18); 

实例:

// class template#include "stdafx.h"#include <iostream>using namespace std;template <class T>class mypair {T a, b;public:mypair (T first, T second)  //构造函数{a= first; b=second;}T getmax();    //成员函数};template <class T>T mypair<T>::getmax ()  //成员函数的实现{T retval;retval = a>b? a : b;return retval;}int _tmain(int argc, _TCHAR* argv[]){mypair <int> myobject (100, 75);cout << myobject.getmax();return 0;}


参考:

Templates


0 0