学习C++模板---模板函数

来源:互联网 发布:网络语爸爸是什么梗 编辑:程序博客网 时间:2024/04/30 17:39
 
学习C++模板---模板函数
模板函数可以解决类型通用性的函数。比如不同的数据类型获取最大值。
 
// atl002.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include <process.h>
#include <iostream>
 
//
//学习C++模板(1)。
//蔡军生2006/12/05
//
 
//
//模板函数。
//蔡军生2006/12/05
//
template< typename T >
T TestMax(T a,T b)
{
     if (a > b)
     {
         return a;
     }
     else
     {
         return b;
     }
}
 
//
//程序入口点。
//
int _tmain(int argc, _TCHAR* argv[])
{
     //int实例。
     int iMax = TestMax< int >( 1,23 );
     std::cout<< "iMax=" << iMax << std::endl;
 
     //float实例。
     float fMax = TestMax< float >( 8.0f,5.0f );
     std::cout<< "fMax=" << fMax << std::endl;
 
     //
     //暂停.
     //
     system("pause");
 
     return 0;
}