函数模板

1个template的声明只能对下面的一个函数起作用。
占位符可以任意起名字,不过T比较常见。

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. template <typename T>
  5. inline T const& Max (T const& a, T const& b)
  6. {
  7. return a < b ? b:a;
  8. }
  9. int main ()
  10. {
  11. int i = 39;
  12. int j = 20;
  13. cout << "Max(i, j): " << Max(i, j) << endl;
  14. double f1 = 13.5;
  15. double f2 = 20.7;
  16. cout << "Max(f1, f2): " << Max(f1, f2) << endl;
  17. string s1 = "Hello";
  18. string s2 = "World";
  19. cout << "Max(s1, s2): " << Max(s1, s2) << endl;
  20. return 0;
  21. }

类模板

1个template的声明只能对下面的一个类/类成员实现函数起作用。
占位符可以任意起名字,不过T比较常见。

  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdlib>
  4. #include <string>
  5. #include <stdexcept>
  6. using namespace std;
  7. template <class T>
  8. class Stack {
  9. private:
  10. vector<T> elems; // 元素
  11. public:
  12. void push(T const&); // 入栈
  13. void pop(); // 出栈
  14. T top() const; // 返回栈顶元素
  15. bool empty() const{ // 如果为空则返回真。
  16. return elems.empty();
  17. }
  18. };
  19. template <class T>
  20. void Stack<T>::push (T const& elem)
  21. {
  22. // 追加传入元素的副本
  23. elems.push_back(elem);
  24. }
  25. template <class T>
  26. void Stack<T>::pop ()
  27. {
  28. if (elems.empty()) {
  29. throw out_of_range("Stack<>::pop(): empty stack");
  30. }
  31. // 删除最后一个元素
  32. elems.pop_back();
  33. }
  34. template <class T>
  35. T Stack<T>::top () const
  36. {
  37. if (elems.empty()) {
  38. throw out_of_range("Stack<>::top(): empty stack");
  39. }
  40. // 返回最后一个元素的副本
  41. return elems.back();
  42. }
  43. int main()
  44. {
  45. try {
  46. Stack<int> intStack; // int 类型的栈
  47. Stack<string> stringStack; // string 类型的栈
  48. // 操作 int 类型的栈
  49. intStack.push(7);
  50. cout << intStack.top() <<endl;
  51. // 操作 string 类型的栈
  52. stringStack.push("hello");
  53. cout << stringStack.top() << std::endl;
  54. stringStack.pop();
  55. stringStack.pop();
  56. }
  57. catch (exception const& ex) {
  58. cerr << "Exception: " << ex.what() <<endl;
  59. return -1;
  60. }
  61. }