Templates and C Generic Techniques
Write type-independent compile-time code.
What is Templates and C Generic Techniques?
Templates generate type-safe implementations from a pattern; C commonly uses macros, void pointers, or C11 _Generic.
Important points
- Understand the C mechanism before comparing the C++ abstraction.
- Use RAII and value semantics to express ownership.
- Prefer type-safe compile-time abstractions over macros and casts.
C and C++ code examples
#include <stdio.h>
int max_int(int left, int right) {
return left > right ? left : right;
}
double max_double(double left, double right) {
return left > right ? left : right;
}
#define MAX(left, right) _Generic((left), \
int: max_int, double: max_double)((left), (right))
int main(void) {
printf("%d %.1f\n", MAX(3, 9), MAX(2.5, 7.0));
}
9 7.0
#include <iostream>
template<class T>
T maximum(const T& left, const T& right) {
return left > right ? left : right;
}
int main() {
std::cout << maximum(3, 9) << ' '
<< maximum(2.5, 7.0) << '\n';
}
9 7
C and C++ comparison
The C11 _Generic expression selects a typed function but requires listing supported types. A C++ function template works for every type satisfying its operations.
C uses naming conventions, callbacks, macros, and explicit context structures.
Language features provide scoped, type-safe, and often zero-overhead abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Write the C mechanism before the C++ abstraction.
- Remove manual cleanup with RAII.
- Check whether the abstraction adds allocations or virtual dispatch.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Array Maximum Find the largest value in a list. Easy
- Min Stack Build a stack that reports its smallest element instantly after any push or pop. Medium