C++ 手冊(cè)教程
/ C++ 模板
C++ 模板
模板是泛型編程的基礎(chǔ),泛型編程即以一種獨(dú)立于任何特定類型的方式編寫(xiě)代碼。
模板是創(chuàng)建泛型類或函數(shù)的藍(lán)圖或公式。庫(kù)容器,比如迭代器和算法,都是泛型編程的例子,它們都使用了模板的概念。
每個(gè)容器都有一個(gè)單一的定義,比如 向量,我們可以定義許多不同類型的向量,比如 vector <int> 或 vector <string>。
您可以使用模板來(lái)定義函數(shù)和類,接下來(lái)讓我們一起來(lái)看看如何使用。
函數(shù)模板
模板函數(shù)定義的一般形式如下所示:
template <class type> ret-type func-name(parameter list) { // 函數(shù)的主體 }
在這里,type 是函數(shù)所使用的數(shù)據(jù)類型的占位符名稱。這個(gè)名稱可以在函數(shù)定義中使用。
下面是函數(shù)模板的實(shí)例,返回兩個(gè)數(shù)種的最大值:
#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; }
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:
Max(i, j): 39 Max(f1, f2): 20.7 Max(s1, s2): World
類模板
正如我們定義函數(shù)模板一樣,我們也可以定義類模板。泛型類聲明的一般形式如下所示:
template <class type> class class-name { . . . }
在這里,type 是占位符類型名稱,可以在類被實(shí)例化的時(shí)候進(jìn)行指定。您可以使用一個(gè)逗號(hào)分隔的列表來(lái)定義多個(gè)泛型數(shù)據(jù)類型。
下面的實(shí)例定義了類 Stack<>,并實(shí)現(xiàn)了泛型方法來(lái)對(duì)元素進(jìn)行入棧出棧操作:
#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"); } // 刪除最后一個(gè)元素 elems.pop_back(); } template <class T> T Stack<T>::top () const { if (elems.empty()) { throw out_of_range("Stack<>::top(): empty stack"); } // 返回最后一個(gè)元素的副本 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; } }
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:
7 hello Exception: Stack<>::pop(): empty stack