c++泛型編程

c++泛型編程

摘自《c++ Primer Plus》第6版16.4ios

泛型編程最初誕生於C++中,由Alexander Stepanov和David Musser創立。目的是爲了實現C++的STL(標準模板庫)。其語言支持機制就是模板(Templates)。c++

面向對象編程關注的是數據,而泛型編程關注的是算法。算法

泛型在C++中的主要實現爲模板函數和模板類。編程

 

(1)定義函數模板(function template

函數模板是一個獨立於類型的函數,能夠產生函數的特定類型版本。函數

模板定義以關鍵字template開始,後接尖括號括住的模板形參表。spa

模板形參能夠是表示類型的類型形參(type parameter),也能夠是表示常量表達式的非類型形參(nontype parameter)。code

使用函數模板時,編譯器會將模板實參綁定到模板形參。編譯器將肯定用什麼類型代替每一個類型形參,用什麼值代替每一個非類型形參,而後產生並編譯(稱爲實例化)該版本的函數。對象

#include <iostream>

template <typename T>
int compare(const T &v1, const T &v2);
using namespace std;

int main()
{

        // compiler instantiates int compare(const int&, const int&)
        cout << compare(1, 0) << endl;
        // // compiler instantiates int compare(const string&, const string&)
        string s1 = "hello", s2 = "world";
        cout << compare(s1, s2) << endl;
        return 0;
}

template <typename T>
int compare(const T &v1, const T &v2)
{
    if (v1 < v2) return -1; 
    if (v2 < v1) return 1;
    return 0;
}

函數模板的性質

1) 函數模板並非真正的函數,它只是C++編譯生成具體函數的一個模子。
2) 函數模板自己並不生成函數,實際生成的函數是替換函數模板的那個函數,好比上例中的add(sum1,sum2),
    這種替換是編譯期就綁定的。
3) 函數模板不是隻編譯一份知足多重須要,而是爲每一種替換它的函數編譯一份。
4) 函數模板不容許自動類型轉換。
5) 函數模板不能夠設置默認模板實參。好比template <typename T=0>不能夠。
C++模版函數的語法
template  <typename 模版參數列表…>
函數返回類型 函數名(形參列表…)
上面兩行能夠合併成一行。開發

 

(2)定義類模板(class template

在定義的類模板中,使用模板形參做爲類型或值的佔位符,在使用類時再提供具體的類型或值。編譯器

與調用函數模板不一樣,使用類模板時,必須爲模板形參顯示指定實參。

#include <iostream>
using namespace std;
template <class numtype>
//定義類模板
class Compare
{
        private :
                numtype x,y;
        public :
                Compare(numtype a,numtype b)
                {x=a;y=b;}
                numtype max( )
                {return (x>y)?x:y;}
                numtype min( )
                {return (x<y)?x:y;}
};
int main( )
{
        Compare<int > cmp1(3,7);  //定義對象cmp1,用於兩個整數的比較
        cout<<cmp1.max( )<<" is the Maximum of two integer numbers."<<endl;
        cout<<cmp1.min( )<<" is the Minimum of two integer numbers."<<endl<<endl;
        Compare<float > cmp2(45.78,93.6);  //定義對象cmp2,用於兩個浮點數的比較
        cout<<cmp2.max( )<<" is the Maximum of two float numbers."<<endl;
        cout<<cmp2.min( )<<" is the Minimum of two float numbers."<<endl<<endl;
        Compare<char> cmp3('a','A');  //定義對象cmp3,用於兩個字符的比較
        cout<<cmp3.max( )<<" is the Maximum of two characters."<<endl;
        cout<<cmp3.min( )<<" is the Minimum of two characters."<<endl;
        return 0;
}

 

類模板的性質

1) 類模板不是真正的類,它只是C++編譯器生成具體類的一個模子。
2) 類模板能夠設置默認模板實參。

 

STL(Standard Template Library,標準模板庫)是C++對泛型編程思想的實現,最先是惠普實驗室開發的。在被引入C++以前該技術就已經存在了很長的一段時間。後來STL成爲ANSI/ISO C++標準的一部分。各個 C++廠商也有各自相應的模板庫,這些庫效率可能很高,但可移植性不必定好。 STL廣義上分爲三類:algorithm(算法)、container(容器)和iterator(迭代器),幾乎全部的代碼都採 用了模板類和模板函數的方式,這相比於傳統的由函數和類組成的庫來講提供了更好的代碼重用機會。

相關文章
相關標籤/搜索