Templates and C Generic Techniques
Templates generate type-safe implementations from a pattern; C commonly uses macros, void pointers, or C11 _Generic.
What is Templates and C Generic Techniques?
Templates generate type-safe implementations from a pattern; C commonly uses macros, void pointers, or C11 _Generic.
Write type-independent compile-time code.
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
main.c
#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
C++
main.cpp
#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
C uses naming conventions, callbacks, macros, and explicit context structures.
C++
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.