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&);

转载于:https://www.cnblogs.com/caty-sky/p/4562364.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值