zoukankan      html  css  js  c++  java
  • C++ Templates编程(模板参数)

    //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)

    作者:长风 Email:844064492@qq.com QQ群:607717453 Git:https://github.com/zhaohu19910409Dz 开源项目:https://github.com/OriginMEK/MEK 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利. 感谢您的阅读。如果觉得有用的就请各位大神高抬贵手“推荐一下”吧!你的精神支持是博主强大的写作动力。 如果觉得我的博客有意思,欢迎点击首页左上角的“+加关注”按钮关注我!
  • 相关阅读:
    浅谈 DML、DDL、DCL的区别
    SQL优化
    Appium定位方式总结
    移动端自动化测试-AppiumApi接口详解
    移动端自动化测试-WTF Appium?
    Selenium-Css Selector使用方法
    Selenium-Switch与SelectApi接口详解
    Selenium-ActionChainsApi接口详解
    Selenium-WebDriverApi接口详解
    Selenium之前世今生
  • 原文地址:https://www.cnblogs.com/zhaohu/p/6502121.html
Copyright © 2011-2022 走看看