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;  
    }  
    

      

     
  • 相关阅读:
    新概念4-16
    答疑汇总-02
    理解Marx-8 9 10晚年的思考 马恩关系再认识 一段思想史的公案
    nefu 116
    nefu 115
    【JZOJ3379】查询【主席树】
    【JZOJ1782】Travel【分层图最短路】
    【洛谷P4550】收集邮票【期望概率】
    【洛谷P1001】A+B Problem
    【JZOJ3339】wyl8899和法法塔的游戏【暴力】
  • 原文地址:https://www.cnblogs.com/YMY666/p/8444115.html
Copyright © 2011-2022 走看看