In C++, Templates provide a mechanism for generic programming. Instead of writing the exact same code multiple times for int, float, and string, you can write it once as a template. The compiler will automatically generate the correct version for you when the code is used.
Suppose you want to write a function that finds the maximum of two numbers. Without templates, you would have to use function overloading for every data type:
int max_val(int a, int b) { return (a > b) ? a : b; }
double max_val(double a, double b) { return (a > b) ? a : b; }
// ... and so on for float, char, etc.With Function Templates, you define a placeholder type (often called T), and the compiler does the rest.
#include <iostream>
using namespace std;
// The template prefix declares 'T' as a generic type
template <typename T>
T findMax(T x, T y) {
return (x > y) ? x : y;
}
int main() {
// The compiler automatically creates an int version
cout << findMax<int>(10, 5) << endl;
// The compiler automatically creates a double version
cout << findMax<double>(3.14, 9.81) << endl;
// Type inference: you don't even need the <type> brackets!
Just like functions, classes can also be templates. This is exceptionally useful for creating data structures (like Stacks, Queues, and Linked Lists) that can hold any type of data.
#include <iostream>
using namespace std;
// A generic Box class that can hold any type of data
template <class T>
class Box {
private:
T contents;
public:
Box(T initial_val) {
contents = initial_val;
}
T getContents() {
return contents;
}
};
int main() {
// We must specify the type when instantiating a class template
Box<int> intBox(100);
Box<string> stringBox("Hello Templates!");
cout <<
When you write a template, you are not writing an actual function or class; you are writing a blueprint for one.
When the compiler encounters findMax<int>(10, 5), it looks at the template and generates a hidden int version of the function in the background. If you never call the template with a float, a float version is never compiled. This process is called Template Instantiation.
A feature in C++ that allows functions and classes to operate with generic types.
A single function definition that can be used for different data types.
A single class definition that can handle different data types (e.g., generic arrays or stacks).
Test your understanding with 2 questions
What keyword is used to declare a template in C++?
When is a template instantiated by the compiler?
2 Modules
2 Modules