Templates in C++ allow programmers to write generic code that can work with different types or values, without having to write separate code for each specific type or value. A template defines a pattern for creating functions or classes that can be customized with different types or values at compile time.
To define a template function, we use the following syntax:
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
In this example, we define a template function called max that takes two arguments of the same type T, and returns the maximum of the two values. The keyword template introduces the template declaration, and the typename T specifies the template parameter, which can be replaced with any valid C++ type. The function body then uses the template parameter to define the behavior of the function.
To call the template function, we specify the template arguments inside angle brackets:
int a = 5, b = 10;
double c = 3.14, d = 2.71;
cout << max<int>(a, b) << endl; // outputs 10
cout << max<double>(c, d) << endl; // outputs 3.14
In this example, we call the max function twice, once with integers and once with doubles. We specify the template argument inside angle brackets, which tells the compiler which version of the template function to instantiate.
To define a template class, we use a similar syntax:
template <typename T>
class Stack {
public:
void push(T value);
T pop();
private:
vector<T> m_data;
};
template <typename T>
void Stack<T>::push(T value) {
m_data.push_back(value);
}
template <typename T>
T Stack<T>::pop() {
T value = m_data.back();
m_data.pop_back();
return value;
}
In this example, we define a template class called Stack that implements a simple stack data structure. We use the same template syntax as for functions, and define the class methods outside of the class declaration, using the template parameter to define the behavior of the methods.
To use the template class, we specify the template argument when declaring an object of the class:
Stack<int> stack;
stack.push(5);
stack.push(10);
cout << stack.pop() << endl; // outputs 10
cout << stack.pop() << endl; // outputs 5
In this example, we create a Stack object that holds integers, and use the push and pop methods to add and remove values from the stack.
Templates are a powerful feature of C++ that allow for generic programming and code reuse. By defining a template function or class, we can write code that works with multiple types or values, without having to duplicate the code for each specific case.