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
- c++:template使用中的常见报错
- C++template
- C template
- C++Template
- emacs中的template
- C++中的模板(template)
- C++中的template学习
- C++中的模板(template)
- C++中的模板(template)
- C++中的模板(template)
- C++中的模板(template)
- C++中的template
- C++中的template
- C++中的template
- golang中的模板template
- WPF中的Template模板
- angular中的ng-template
- list c++template
- 进度条progress
- 操作系统(计算机管理控制程序)2
- Sencha-逻辑-Controller(控制器)(官网文档翻译2)
- Java Statement 对象描述
- 操作系统(计算机管理控制程序)2
- C++中的template
- 操作系统(计算机管理控制程序)2
- with(nolock)的介绍
- 操作系统(计算机管理控制程序)5
- duplicate symbol _OBJC_CLASS 错误处理方法
- [摘]Spring的jar包解析
- ruby metaprogramming examples
- 操作系统(计算机管理控制程序)6
- Linux下Apache和PHP的安装与配置