c++模板與泛型編程基礎


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

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

復制代碼
// implement strcmp-like generic compare function
template <typename T>
int compare(const T &v1, const T &v2)
{
    if (v1 < v2) return -1;
    if (v2 < v1) return 1;
    return 0;
}
復制代碼

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

模板形參可以是表示類型的類型形參(type parameter),也可以是表示常量表達式的非類型形參(nontype parameter)。上面程序中的T是類型形參。

// compiler instantiates int compare(const int&, const int&)
cout << compare(1, 0) << endl;
// compiler instantiates int compare(const string&, const string&)
string s1 = “hi”, s2 = “world”;
cout << compare(s1, s2) << endl;

使用函數模板時,編譯器會將模板實參綁定到模板形參。編譯器將確定用什么類型代替每個類型形參,用什么值代替每個非類型形參,然后產生並編譯(稱為實例化)該版本的函數。

上面的例子中,編譯器用int代替T創建第一個版本,用string代替T創建第二個版本。

函數模版不支持返回值

(2)定義類模板(class template

在定義的類模板中,使用模板形參作為類型或值的占位符,在使用類時再提供具體的類型或值

復制代碼
template <typename Type> 
class Queue
{
public:
    Queue();
    Type & front();
    const Type & front() const;
    void push(const Type &);
    void pop();
    bool empty() const;
private:
    // …
};
復制代碼

與調用函數模板不同,使用類模板時,必須為模板形參顯示指定實參

Queue<int> qi; // Queue that holds ints
Queue<string> qs; // Queue that holds strings

 

 

 


免責聲明!

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



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