Templates: Writing Generic Code
6 min read
π Welcome to the "Don't Repeat Yourself" Dojo
Welcome back, C++ padawan! π₯ Today, we are tackling one of the most powerful (and admittedly, sometimes scary) features of C++: Templates.
If you have ever found yourself writing the same function three times just to handle int, float, and double, you have officially entered the "Boilerplate Zone." Itβs boring, itβs prone to errors, and frankly, we have better things to doβlike arguing about tabs vs. spaces.
Templates allow you to write code that works with any data type. It is the blueprint, not the building. Let's dive in! π
1. Function Templates: Type-Independent Algorithms
π The Problem
Imagine you need a function to find the maximum of two numbers.
Without Templates:
int getMax(int a, int b) {
return (a > b) ? a : b;
}
double getMax(double a, double b) {
return (a > b) ? a : b; // π heavily breathing
}
char getMax(char a, char b) {
return (a > b) ? a : b; // π make it stop
}If you want to support 10 types, you write 10 functions. If you find a bug in the logic, you fix it in 10 places. This is maintenance hell.
π‘ The Solution: Function Templates
A Function Template is a blueprint. You tell the compiler: "I don't care what the data type is. Just call it T, and generate the correct version when I actually use it."
π» The Syntax
We use the keyword template followed by template parameters inside < >.
#include <iostream>
// The Blueprint
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
// Usage
std::cout << getMax(5, 10) << std::endl; // Compiler creates getMax(int, int)
std::cout << getMax(3.5, 9.1) << std::endl; // Compiler creates getMax(double, double)
std::cout << getMax('a', 'z') << std::endl; // Compiler creates getMax(char, char)
return 0;
}π§ How it Works (Under the Hood)
Templates are not compiled into code directly. They are instantiated at compile time.
- When you call
getMax(5, 10), the compiler sees you passed integers. - It looks at the template.
- It silently generates a specific function where
Tis replaced byint. - This looks exactly like the manual version you would have written, but the compiler did the typing for you. Thanks, compiler! π€
Note:
typename Tandclass Tare interchangeable in this context. You will see both in the wild.typenameis generally preferred in modern C++ for clarity becauseTcan beint(which isn't a class).
2. Class Templates: Generic Data Structures
π The Problem
You want to build a "Box" class that holds an item.
- Monday: You need a
IntBoxto hold an integer. - Tuesday: You need a
StringBoxto hold a text. - Wednesday: You realize you need a
ZombieBoxfor your game entity.
Creating a new class for every data type violates the DRY (Don't Repeat Yourself) principle.
π‘ The Solution: Class Templates
Just like function templates, we can make the entire class generic.
π» The Syntax
#include <iostream>
// Class Template Definition
template <typename T>
class Box {
private:
T item;
public:
Box(T i) : item(i) {}
T getItem() {
return item;
}
void setItem(T i) {
item = i;
}
};
int main() {
// Usage: We MUST specify the type inside < >
Box<int> intBox(123);
Box<std::string> strBox("Hello World");
std::cout << intBox.getItem() << std::endl;
std::cout << strBox.getItem() << std::endl;
return 0;
}π€ Industry Insight
You have likely already used this without knowing! The Standard Template Library (STL) is built entirely on this.
std::vector<int>is just a class template namedvectorinstantiated withint.std::vector<std::string>is the same template instantiated withstring.
3. Template Instantiation and Parameters
Template Parameters (More than just Types)
You aren't limited to just typename T. You can also pass values (Non-Type Template Parameters), usually integers. This is how std::array works.
Example: A Fixed-Size Array Wrapper
template <typename T, int Size>
class StaticArray {
private:
T data[Size]; // Size is known at compile time!
public:
int getSize() const { return Size; }
};
int main() {
StaticArray<int, 5> myArr; // Creates an array of 5 ints
// StaticArray<int, 10> myArr2; // This is a DIFFERENT type to the compiler!
}Implicit vs. Explicit Instantiation
- Implicit: The compiler guesses the type based on arguments (mostly for functions).
getMax(5, 6)->Tisint.
- Explicit: You tell the compiler exactly what
Tis.getMax<double>(5, 6)-> ForcesTto bedouble, even though 5 and 6 are ints.
β οΈ The "Linker Error" Nightmare (CRITICAL)
This is the #1 issue beginners face.
Rule: Template definitions usually need to go in the Header File (.h), not the Source File (.cpp).
Why?
If you put the template logic in a .cpp file, the compiler compiles that file separately. When it compiles your main.cpp, it doesn't know how to generate the code for Box<int> because the blueprint is hidden inside another .cpp file that hasn't been linked yet.
Best Practice:
Put your template declaration and implementation in the header file. Sometimes these are saved as .hpp or .tpp to distinguish them, but .h works fine.
4. Practical Use Cases for Templates
In the real world, you won't always write your own templates, but you will consume them daily.
A. The Standard Template Library (STL)
This is the bread and butter of C++.
- Containers:
std::vector<T>,std::list<T>,std::map<K, V>. - Smart Pointers:
std::unique_ptr<T>,std::shared_ptr<T>.
B. Generic Algorithms
Writing a sorting algorithm for integers, then another for floats, then another for custom objects is a waste of time.std::sort is a template function that works on anything that can be compared.
#include <vector>
#include <algorithm> // Contains the templates
#include <iostream>
int main() {
std::vector<int> nums = {4, 2, 5, 1, 3};
// std::sort is a function template!
std::sort(nums.begin(), nums.end());
for(int n : nums) std::cout << n << " ";
return 0;
}C. Type Traits & Metaprogramming (The Advanced Stuff)
In high-performance libraries (like game engines or financial systems), developers use templates to perform calculations at compile time to save CPU cycles at runtime. This involves "Type Traits" (checking if T is an integer, or a pointer, etc.).
π§ͺ Quick Review
- Templates let you write code once for multiple data types.
- Function Templates automate algorithm generation (
sort,max). - Class Templates automate data structure generation (
vector,Box). - Template Definitions usually live in header files (
.h). - Use the STL; don't reinvent the generic wheel unless you are studying.
π References & Further Reading
- CppReference (The Bible of C++):
- C++ FAQ (IsoCpp):
Happy Coding! π§
Challenge
You are tasked with implementing a generic, fixed-size array container using C++ templates.
1. Class Template: FixedArray
Create a class template named FixedArray that takes two template parameters:
- A type parameter
Tfor the element type. - A non-type parameter
size_t Nfor the fixed size of the array.
The class must have the following public interface:
- A
size()method that returns the sizeNof the array. This method should beconstexpr. - An
at(size_t index)method that returns aT&reference to the element at the given index. This method must perform bounds checking and throwstd::out_of_rangeif the index is out of bounds (i.e.,index >= N). - An overloaded
constversion ofat(size_t index)that returns aconst T&reference. This should also perform bounds checking.
The underlying data should be stored in a private C-style array.
2. Function Template: fill
Create a non-member function template named fill that takes two arguments:
- A reference to a
FixedArray<T, N>object. - A constant reference to a value of type
T.
This function should set every element in the given FixedArray to the provided value.
Expected result
Your final code should contain a complete and correct implementation for both the FixedArray class template and the fill function template.
A correct implementation will satisfy the following criteria:
FixedArrayClass Template:- The template declaration is
template <typename T, size_t N>. - It contains a private member
T m_data[N];. - The
size()method is public,constexpr, and returnsN. - The
at(size_t index)method returns aT&, checks ifindex >= N, throwsstd::out_of_rangeon failure, and returnsm_data[index]on success. - The
const at(size_t index)method returns aconst T&and has the same bounds-checking logic.
- The template declaration is
fillFunction Template:- The template declaration is
template <typename T, size_t N>. - The function signature is
void fill(FixedArray<T, N>& arr, const T& value). - The implementation uses a loop (e.g., a for loop from
0toarr.size()) to assignvalueto each element of the array, for instance by using theat()method.
- The template declaration is