C++ Templates
Templates are the foundation of generic programming, which is a way of writing code that is independent of any specific type.
A template is a blueprint or formula for creating generic classes or functions. Library containers, such as iterators and algorithms, are examples of generic programming, and they all use the concept of templates.
Each container has a single definition, such asvectorWe can define many different types of vectors, such asvector <int>orvector <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:
Here, type is a placeholder name for the data type used by the function. This name can be used in the function definition.
The following is an example of a function template that returns the maximum of two numbers:
Example
When the above code is compiled and executed, it produces the following results:
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,typeIt is a placeholder type name that can be specified when the class is instantiated. You can use a comma-separated list to define multiple generic data types.
The following example defines the class Stack<> and implements generic methods to push and pop elements:
Example
When the above code is compiled and executed, it produces the following results:
7 hello Exception: Stack<>::pop(): empty stackother extensions