c / expert
Snippet
Type-Generic Function Overloading via C11 _Generic Selection
C11 introduced the _Generic keyword to enable compile-time dispatch based on argument types. This allows developers to construct type-safe polymorphic macros without runtime dispatch overhead.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>#include <math.h>double process_double(double val) { return sin(val); }float process_float(float val) { return sinf(val); }long double process_ldouble(long double val) { return sinl(val); }#define compute_sine(X) _Generic((X), \float: process_float, \double: process_double, \long double: process_ldouble \)(X)int main(void) {float f = 1.57f;double d = 3.14159;printf("Float sine: %f\n", compute_sine(f));printf("Double sine: %f\n", compute_sine(d));return 0;}
Breakdown
1
_Generic((X), float: process_float, ...)
Evaluates the static type of expression X at compile time and resolves to the matching function pointer.
2
)(X)
Invokes the function selected by the generic expression, passing X as the parameter.