C++中的模板template

  這個是C++中的模板..template<typename T> 這個是定義模板的固定格式,規定了的..模板應該能夠理解到它的意思吧.. 好比你想求2個int float 或double型變量的值,只須要定義這麼一個函數就能夠了,假如不用模板的話,你就必須針對每種類型都定義一個sum函數..int sum(int, int);float sum(float, float);double sum(double, double);ios

 

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
相關文章
相關標籤/搜索