C++中的模板template


  這個是C++中的模板..template<typename T> 這個是定義模板的固定格式,規定了的..模板應該可以理解到它的意思吧.. 比如你想求2個int float 或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(模板)的使用方法。

 

  1.  
    <pre name= "code" class="cpp">// TemplateTest.cpp : 定義控制台應用程序的入口點。
  2.  
    ///<summary>
  3.  
    ///測試C++中的template(模板)的使用方法 最新整理時間2016.5.21
  4.  
    ///</summary>
  5.  
    ///<remarks>1:template的使用是為了簡化不同類型的函數和類的重復定義.
  6.  
    ///<remarks>2:char類型變量c,d輸入的都是字母,不是數字,如輸入32則c=3,d=2.
  7.  
    #include "stdafx.h"
  8.  
    #include <iostream>
  9.  
    #include< vector>
  10.  
    using namespace std;
  11.  
    template <typename T>
  12.  
    T mmax(T a,T b)
  13.  
    {
  14.  
    return a>b?a:b;
  15.  
    }
  16.  
    int _tmain(int argc, _TCHAR* argv[])
  17.  
    {
  18.  
    cout<<"Please enter the value of a and b:"<<endl;
  19.  
    int a,b;
  20.  
    cin>>a>>b;
  21.  
    cout<<mmax(a,b)<<endl;
  22.  
    cout<<"Please enter the value of c and d:"<<endl;
  23.  
    char c,d;
  24.  
    cin>>c>>d;
  25.  
    cout<<mmax(c,d)<<endl;
  26.  
    cout<<"Please enter the value of f and g:"<<endl;
  27.  
    double f,g;
  28.  
    cin>>f>>g;
  29.  
    cout<<mmax(f,g)<<endl;
  30.  
    while(1);
  31.  
    return 0;
  32.  
    }
    轉載:https://blog.csdn.net/fightingforcv/article/details/51472586


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM