C++ 模板

C++ 模板

模板是泛型程式設計的基礎,泛型程式設計即以一種獨立於任何特定型別的方式編寫程式碼。

模板是建立泛型類或函式的藍圖或公式。庫容器,比如迭代器和演算法,都是泛型程式設計的例子,它們都使用了模板的概念。

每個容器都有一個單一的定義,比如 向量,我們可以定義許多不同型別的向量,比如 vector <int>vector <string>

您可以使用模板來定義函式和類,接下來讓我們一起來看看如何使用。

函式模板

模板函式定義的一般形式如下所示:

template <typename type> ret-type func-name(parameter list) { // 函式的主體 }

在這裡,type 是函式所使用的資料型別的佔位符名稱。這個名稱可以在函式定義中使用。

下面是函式模板的例項,返回兩個數中的最大值:

例項

#include <iostream> #include <string> using namespace std; template <typename T> inline T const& Max (T const& a, T const& b) { return a < b ? b:a; } int main () { int i = 39; int j = 20; cout << "Max(i, j): " << Max(i, j) << endl; double f1 = 13.5; double f2 = 20.7; cout << "Max(f1, f2): " << Max(f1, f2) << endl; string s1 = "Hello"; string s2 = "World"; cout << "Max(s1, s2): " << Max(s1, s2) << endl; return 0; }

當上面的程式碼被編譯和執行時,它會產生下列結果:

Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World

類模板

正如我們定義函式模板一樣,我們也可以定義類模板。泛型類宣告的一般形式如下所示:

template <class type> class class-name {
.
.
.
}

在這裡,type 是佔位符型別名稱,可以在類被例項化的時候進行指定。您可以使用一個逗號分隔的列表來定義多個泛型資料型別。

下面的例項定義了類 Stack<>,並實現了泛型方法來對元素進行入棧出棧操作:

例項

#include <iostream> #include <vector> #include <cstdlib> #include <string> #include <stdexcept> using namespace std; template <class T> class Stack { private: vector<T> elems; // 元素 public: void push(T const&); // 入棧 void pop(); // 出棧 T top() const; // 返回棧頂元素 bool empty() const{ // 如果為空則返回真。 return elems.empty(); } }; template <class T> void Stack<T>::push (T const& elem) { // 追加傳入元素的副本 elems.push_back(elem); } template <class T> void Stack<T>::pop () { if (elems.empty()) { throw out_of_range("Stack<>::pop(): empty stack"); } // 刪除最後一個元素 elems.pop_back(); } template <class T> T Stack<T>::top () const { if (elems.empty()) { throw out_of_range("Stack<>::top(): empty stack"); } // 返回最後一個元素的副本 return elems.back(); } int main() { try { Stack<int> intStack; // int 型別的棧 Stack<string> stringStack; // string 型別的棧 // 操作 int 型別的棧 intStack.push(7); cout << intStack.top() <<endl; // 操作 string 型別的棧 stringStack.push("hello"); cout << stringStack.top() << std::endl; stringStack.pop(); stringStack.pop(); } catch (exception const& ex) { cerr << "Exception: " << ex.what() <<endl; return -1; } }

當上面的程式碼被編譯和執行時,它會產生下列結果:

7
hello
Exception: Stack<>::pop(): empty stack