C++模版使用

來源:互聯網
上載者:User
一.基本
以下的模版類型關鍵字class在新C++標準中建議使用typename代替.
1.1通用函數
template <class Ttype> re-type func-name(parameter list)
{
       //body of funtion
}
例如:
template <class X> void swap(X &a,X &b)
{
       X temp;
       temp = a;
       a = b;
       b = temp;
}

#include <iostream>
using namespace std;
int main()
{
       int i=10, j=20;
       swap(i, j);
       cout<<"swapped i, j:"<<i<<j<<'\n';
}
1.2通用類
template <class Ttype> class class-name
{
       //body of class
}
例如:
#include <iostream>
using namespace std;
const int SIZE = 10;
template <class StackType> class stack
{
      StackType stack[SIZE];
      int tos;                                                            //棧頂索引
public:
      stack()  { tos = 0;}
      void push(StackType ob)
       {
              if(tos==SIZE)
              {
                      cout<<"stack is full.\n";
                      return;
              }
              stack[tos]=ob;
              tos++;
       }
       StackType pop()
       {
              if(tos==0)
              {
                     cout<<"stack is empty.\n");
                      return 0;
              }
              tos--;
              return stack[tos];
       }
}

int main()
{
        stack<char> s1;
        s1.push('a');
        s1.push('b');
        while(s1.tos)
        {
               cout<<"pop s1:"<<s1.pop()<<'\n';
        }
}
本質上,我認為模版實現了通用邏輯的定義,使演算法獨立於資料類型(由於實際程式一定要先給出資料類型,所以編譯器需要先解析模版,類似於宏命令).如上面的棧類,實際可能有整型棧或浮點型棧等.如果不使用模版,我們需要針對每個類型編一個棧類,其實操作又是完全一樣.順便說一下:STL就是一批高手精心設計的模版.

二.提高
2.1多類型模版
模版類型可以有多個,如:
template <typename OrgType, typename DesType> DesType covent(OrgType org)
{
       return (DesType)org;
}
2.2重載
同類等類似,模版也可以重載.如:定義同名的函數重載函數模版或定義另一個同名但類型定義數不同的模版.
template<> void swap<int>(int &a, int &b)
{
       int temp;
       temp = a;
       a =b ;
       b = temp;
}
2.3預設類型
template <class X=int>  class myclass
{
        //body of class
}
2.4使用無型別參數
template <class Stype, int size> class stack
{
      Stype stackBuffer[size];
      ... ...
}
調用時:
stack<int , 20>  intStack;
2.5typenaem和export關鍵字
typename 通知編譯器模版聲明中使用的名字是類型名,而不是對象名,前面的模版類型關鍵字class可以用它代替.
export用在template聲明之前,使其它檔案只通過指定模版聲明而不是全部複製來使用其它檔案中定義的模版.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.