Happy file C++ template

C++ templates

Templates are the foundation of generic programming, which is writing code in a way that is independent of any particular type.

A template is a blueprint or formula for creating a generic class or function. Library containers, such as iterators and algorithms, are examples of generic programming, and they both use the concept of templates.

Every container has a single definition, like  a vector  , and we can define many different types of vectors, like  vector<int>  or  vector<string> .

You can use templates to define functions and classes, let's take a look at how to use them.

function template

The general form of a template function definition is as follows:

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

Here, type is a placeholder name for the data type used by the function. This name can be used in function definitions.

Here is an example of a function template that returns the maximum of two numbers:

example

#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;
}

When the above code is compiled and executed, it produces the following result:


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

class template

Just as we define function templates, we can also define class templates. The general form of a generic class declaration is as follows:


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

Here, type  is a placeholder type name that can be specified when the class is instantiated. You can define multiple generic data types using a comma-separated list.

The following example defines the class Stack<>, and implements a generic method to push and pop elements from the stack:

example

#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;
    } 
}

When the above code is compiled and executed, it produces the following result:


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

Guess you like

Origin blog.csdn.net/m0_74760716/article/details/131504727