c / expert
Snippet
Typgenerische Funktionsüberladung durch C11 _Generic-Auswahl
C11 führte das Schlüsselwort _Generic ein, um eine Dispatch-Logik zur Kompilierzeit basierend auf Argumenttypen zu ermöglichen. Dies erlaubt typsichere polymorphe Makros ohne Laufzeit-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;}
Erklärung
1
_Generic((X), float: process_float, ...)
Wertet den statischen Typ des Ausdrucks X zur Kompilierzeit aus und löst den passenden Funktionszeiger auf.
2
)(X)
Ruft die durch den generischen Ausdruck ausgewählte Funktion auf und übergibt X als Parameter.