C ++模板

模板是泛型编程的基础,它涉及以独立于任何特定类型的方式编写代码.

模板是用于创建泛型类的蓝图或公式或一个功能.像迭代器和算法这样的库容器是泛型编程的例子,并且是使用模板概念开发的.

每个容器都有一个定义,例如 vector ,但我们可以定义许多不同类型的向量,例如 vector< int> vector< string> .

您可以使用模板来定义函数和类,让我们看看它们是如何工作和减去的;

函数模板

模板的一般形式函数定义显示在这里 :

template <class type> ret-type func-name(parameter list) {
   // body of function
}

这里,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;    // elements 

   public: 
      void push(T const&);  // push element 
      void pop();               // pop element 
      T top() const;            // return top element 
      
      bool empty() const {      // return true if empty.
         return elems.empty(); 
      } 
}; 

template <class T>
void Stack<T>::push (T const& elem) { 
   // append copy of passed element 
   elems.push_back(elem);    
} 

template <class T>
void Stack<T>::pop () { 
   if (elems.empty()) { 
      throw out_of_range("Stack<>::pop(): empty stack"); 
   }
   
   // remove last element 
   elems.pop_back();         
} 

template <class T>
T Stack<T>::top () const { 
   if (elems.empty()) { 
      throw out_of_range("Stack<>::top(): empty stack"); 
   }
   
   // return copy of last element 
   return elems.back();      
} 

int main() { 
   try {
      Stack<int>         intStack;  // stack of ints 
      Stack<string> stringStack;    // stack of strings 

      // manipulate int stack 
      intStack.push(7); 
      cout << intStack.top() <<endl; 

      // manipulate string stack 
      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