Templates
Templates allow you to write generic code that works with any data type. They are the foundation of the STL.
Function Templates
Instead of writing multiple functions for int, double, etc., write one template.
| template <typename T>
T max_value(T a, T b) {
return (a > b) ? a : b;
}
int i = max_value(10, 20); // T is int
double d = max_value(3.14, 2.5); // T is double
|
Template Argument Deduction
The compiler usually deduces T automatically. You can also specify it explicitly:
| max_value<double>(10, 2.5); // Forces T=double, 10 is converted
|
Class Templates
Useful for container classes.
| template <typename T>
class Box {
private:
T value;
public:
Box(T v) : value(v) {}
T get() const { return value; }
};
Box<int> intBox(123);
Box<std::string> strBox("Hello");
|
Template Specialization
You can provide a specific implementation for a particular type.
| // Generic
template <typename T>
void print(T val) {
std::cout << val << "\n";
}
// Specialization for bool
template <>
void print<bool>(bool val) {
std::cout << (val ? "True" : "False") << "\n";
}
|
Non-Type Template Parameters
Templates can take values, not just types.
| template <typename T, int Size>
class Array {
T data[Size];
public:
int get_size() const { return Size; }
};
Array<int, 10> my_array; // Size is known at compile-time
|
Variadic Templates (C++11)
Templates that accept an arbitrary number of arguments.
| template<typename T>
T sum(T t) {
return t;
}
template<typename T, typename... Args>
T sum(T t, Args... args) {
return t + sum(args...);
}
int total = sum(1, 2, 3, 4, 5); // 15
|