zoukankan      html  css  js  c++  java
  • 【转载】C++中的模板template <typename T>

    从一位大佬的程序中看到的,好像挺牛的!!

    这个是C++中的模板..template<typename T> 这个是定义模板的固定格式,规定了的..模板应该可以理解到它的意思吧.. 比如你想求2个intfloat 或double型变量的值,只需要定义这么一个函数就可以了,假如不用模板的话,你就必须针对每种类型都定义一个sum函数..int sum(int, int);float sum(float, float);double sum(double, double);

    1.因为T是一个模版实例化时才知道的类型,所以编译器更对T不知所云,为了通知编译器T是一个合法的类型,使用typename语句可以避免编译器报错。 
    2.template < typename var_name > class class_name; 表示var_name是一个类型, 在模版实例化时可以替换任意类型,不仅包括内置类型(int等),也包括自定义类型class。 换句话说,在template<typename Y>和template<class Y>中, 
    typename和class的意义完全一样。 
    建议在这种语句中尽可能采用typename,以避免错觉(因为只能替换class,不能只换int), 
    这也是C++新标准引进typename关键词的一个初衷


     下面我们以求两个数中的最大值为例介绍Template(模板)的使用方法。
    <pre name="code" class="cpp">// TemplateTest.cpp : 定义控制台应用程序的入口点。  
    ///<summary>  
    ///测试C++中的template(模板)的使用方法 最新整理时间2016.5.21  
    ///</summary>  
    ///<remarks>1:template的使用是为了简化不同类型的函数和类的重复定义.  
    ///<remarks>2:char类型变量c,d输入的都是字母,不是数字,如输入32则c=3,d=2.  
    #include "stdafx.h"  
    #include <iostream>  
    #include<vector>  
    using namespace std;  
    template <typename T>  
    T mmax(T a,T b)  
    {  
        return a>b?a:b;  
    }  
    int _tmain(int argc, _TCHAR* argv[])  
    {  
        cout<<"Please enter the value of a and b:"<<endl;  
        int a,b;  
        cin>>a>>b;  
        cout<<mmax(a,b)<<endl;  
        cout<<"Please enter the value of c and d:"<<endl;  
        char c,d;  
        cin>>c>>d;  
        cout<<mmax(c,d)<<endl;  
        cout<<"Please enter the value of f and g:"<<endl;  
        double f,g;  
        cin>>f>>g;  
        cout<<mmax(f,g)<<endl;  
        while(1);  
        return 0;  
    }  
    

      

     
  • 相关阅读:
    应用实例:用户登录(2009.10.23)
    ASP.NET学习笔记:服务器控件 (2009.11.9)
    小实例:模拟电话簿
    用Iframe实现左边TreeView导航,右边显示相应内容的布局
    HTML&CSS&JaveScript学习笔记(2009.11.19)
    C#中问号(?)的用法
    GridView的简单分页等
    GridView正反双向排序
    代码理解(2009.11.20)
    ASP.NET学习笔记:数据库操作 (2009.11.10)
  • 原文地址:https://www.cnblogs.com/YMY666/p/8444115.html
Copyright © 2011-2022 走看看