Overview of Generic Code
When writing modern C++, it is important not to confuse metaprogramming with basic template usage. While both help us write flexible code, they solve problems at different scales.
Table of Contents
The 3 Ways to Write Generic Code
When you need a function to handle different data types, you generally have three approaches:
| Approach | How It Works | Best Used For |
|---|---|---|
| Overloading | Writing a separate function for every single type. | Small, specific cases where logic differs wildly per type. |
| Specialization | Creating a general template, but overriding it for a specific type. | Handling “exceptions to the rule” in your templates. |
| Metaprogramming | Writing logic that evaluates types at compile-time and adapts automatically. | Large-scale generic code based on type traits or concepts. |
The Power of Metaprogramming
Basic templates prevent you from rewriting the exact same code for different types. Metaprogramming takes this a step further.
The Golden Rule
Metaprogramming reduces your workload from writing one function per type to writing one function per category of types.
A Real-World Example
Imagine you want to print different kinds of data. You might have:
- 50 Custom Classes (House, Person, Car, Dog…) that all have a
.toString()method. - 10 Container Types (
std::vector,std::set,std::list,std::map…). - 10 Primitive Types (
int,float,double…).
How do we solve this efficiently?
If you use pure Overloading Bad Idea, you would have to write 70 different functions!
By using Metaprogramming Modern C++ (like if constexpr and type traits), you can group these into categories. You reduce your workload from 70 separate functions down to just 3 template functions:
- One for classes with a
.toString()method. - One for iterable containers.
- One for basic primitives.
Explore Templates Back to Multithreading
Table of contents
- Basics
- Two-Phase Lookup & Dependent Names
- Alias Templates and Template Parameters
- Template Arguments
- Template Specialization (Primary, Partial, and Full)
- Evolution of Compile-Time Branching
- Specializing Classes vs. Functions (The Overload Trap)
- Template Instantiation Strategies
- Inlining and Translation Units
- Template Constraints & Concepts