Templates are a powerful feature of C++ that allow you to write generic programs. In simple terms, you can create a single function or class to work with different data types.
Instead of writing multiple functions to add integers, add floats, and add doubles, you can write one template function that adds any data type. This is central to C++'s Generic Programming paradigm.
We use the template keyword to create templates. Following that, we use angle brackets < > to specify a generic data type, usually named T (for Type).
template <typename T>
T myMax(T x, T y) {
return (x > y) ? x : y;
}
#include <iostream> using namespace std;// Create a generic template function template <typename T> T add(T a, T b) { return a + b; }
int main() { // Call add with integers cout << "Int result: " << add<int>(5, 10) << "\n";
// Call add with doubles cout << "Double result: " << add<double>(5.5, 2.2) << "\n";
return 0; }
Notice how the compiler automatically generates the correct function version based on the data type passed in the angle brackets <int> or <double>. (Actually, C++ can often deduce the type automatically, so add(5, 10) works too!)
Just like functions, classes can also be templates. This is extremely useful for creating data structures like Lists, Queues, and Stacks that can hold any type of data.
#include <iostream> using namespace std;template <typename T> class Box { private: T item; public: void setItem(T i) { item = i; } T getItem() { return item; } };
int main() { // A Box that holds an integer Box<int> intBox; intBox.setItem(100); cout << "Integer Box: " << intBox.getItem() << "\n";
// A Box that holds a character Box<char> charBox; charBox.setItem('Z'); cout << "Character Box: " << charBox.getItem() << "\n";
return 0; }
The Standard Template Library (STL) in C++, which contains vectors, lists, and maps, is built entirely using this concept!
Which keyword is used to start a template definition?