แม่แบบ C ++
แม่แบบการเขียนโปรแกรมทั่วไปการเขียนโปรแกรมทั่วไปที่เป็นลักษณะแบบสแตนด์อะโลนที่จะชนิดใดเขียนโค้ด
แม่แบบในการสร้างระดับทั่วไปหรือฟังก์ชั่นพิมพ์เขียวหรือสูตร ภาชนะห้องสมุด iterators และขั้นตอนวิธีการเช่นนี้เป็นตัวอย่างของการเขียนโปรแกรมทั่วไปพวกเขาทั้งหมดใช้แนวคิดของแม่แบบ
แต่ละภาชนะมีความหมายเดียวเช่นเวกเตอร์เราสามารถกำหนดจำนวนของชนิดที่แตกต่างกันของเวกเตอร์เช่นเวกเตอร์ <int>หรือเวกเตอร์ <String>
คุณสามารถใช้แม่แบบในการกำหนดฟังก์ชั่นและการเรียนลองมาดูที่วิธีการใช้
แม่แบบฟังก์ชั่น
รูปแบบทั่วไปของฟังก์ชั่นแม่แบบที่ถูกกำหนดให้ดังต่อไปนี้:
template <class type> ret-type func-name(parameter list) { // 函数的主体 }
ที่นี่ประเภทเป็นหน้าที่ของชนิดข้อมูลที่ใช้ชื่อตัวยึด ชื่อที่สามารถนำมาใช้ในความหมายฟังก์ชั่น
นี่คือตัวอย่างของแม่แบบฟังก์ชั่นที่ใช้งานส่งกลับจำนวนสูงสุดของสองชนิด:
#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 { . . . }
นี่เป็นชื่อชนิดประเภทตัวยึดสามารถระบุได้ในระดับที่มีการยกตัวอย่างคุณสามารถใช้รายการคั่นด้วยเครื่องหมายจุลภาคเพื่อกำหนดหลายชนิดข้อมูลทั่วไป
ตัวอย่างต่อไปนี้กำหนดระดับกอง <> และใช้วิธีทั่วไปเพื่อให้การดำเนินงานของสแต็คป๊อปในองค์ประกอบ:
#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