C++ Templates 学习历程一

一、定义max函数模板

//basics/mas.hpp
temeplate<typename T>
inline T const& max (T const& a, T const&  b)
{
    return a < b ? b : a;
}

  模板参数的声明

template <comma-separated-list-of-paramaters>
//temeplate<参数列表,用逗号隔开>

模板max()的另一种等价定义

temeplate <class T>
inline T const& max (T const& a, T const&  b)
{
    return a < b ? b : a;
}

使用模板

//basics/max.cpp
#include<iostream>
#include<string>
#include"max.hpp"

int main()
{
   int i = 42;
   std::cout<<"max( 7,i ) : "<<::max( 7, i )<<std::endl;  

  double f1 = 3.4;
  double f2 = -6.7;
  std::cout<<"max( f1,f2 ) : "<<::max( f1, f2 )<<std::endl;  

  string s1="mathmatics";
  string s2="math";
  std::cout<<"max( s1,s2 ) : "<<::max( s1, s2 )<<std::endl;  
}

max()模板每次调用前面都有域限定符 :: ,是为了确认调用的是全局名字空间中的max()。

用具体类型代替模板参数叫做实例化。它产生了一个模板的实例,即:

max()的第一次调用为int实例化了max模板,就像具有如下单独的声明和实现一样

const int& max( int const&, int const&);
posted @ 2015-06-09 00:36  ChCaty  阅读(254)  评论(0编辑  收藏  举报