首页 > 编程语言 > 详细

C++ Templates编程(模板参数)

时间:2017-03-04 18:55:35      阅读:228      评论:0      收藏:0      [点我收藏+]

//file max.hpp

template <typename T>

//template<class T>

inline T const& max (T const& a,T const& b)

{

return a<b?b:a;

}

 

//file 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;

 

  std::string s1 = "mathematics";

  std::string s2 = "math";

  std::cout<<"max(s1,s2):"<<::max(s1,s2)<<std::endl;

}

 

//out

max(7,i):42

max(f1,f2):6.7

max(s1,s2):mathematics

 

/*******/

max(4,7) //OK

msx(4,4.2) //error

有三种方法解决:

1:对实参进行强制类型转化,使他们可以相互匹配

  max(static_cast<double>(4),4.2)

2:显示指定(或者限定)T的类型

  max<double>(4,4.2)

3:指定两个参数可以具有不同的类型

  template<typename T1,typename T2>

      inline T1 max(T1 const& a,T2 const& b)

  {

    return a<b?b:a;

  }

 

//解决返回类型的问题

template <typename T1,typename T2,typename RT>

inline RT max(T1 const& a,T2 const& b);

...

max<int,double,double>(4,4.2)//ok 但是麻烦

 

/*****/

template <typename RT,typename T1,typename T2>

inline RT max(T1 const& a,T2 const& b)

...

max<double>(1.4,2)

C++ Templates编程(模板参数)

原文:http://www.cnblogs.com/zhaohu/p/6502121.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!