cpp / intermediate
Snippet
Statische Template-Verzweigung mit Constexpr If
Die 'if constexpr'-Anweisung ermöglicht Verzweigungen zur Kompilierzeit. Der nicht gewählte Zweig wird vom Compiler verworfen, was für die Template-Metaprogrammierung wichtig ist, um die Instanziierung von ungültigem Code für bestimmte Typen zu verhindern.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>#include <type_traits>template <typename T>void process_value(T val) {if constexpr (std::is_floating_point_v<T>) {std::cout << "Processing float: " << val << std::endl;} else {std::cout << "Processing non-float value" << std::endl;}}int main() {process_value(3.14); // Branches at compile-timeprocess_value(42); // Discards the float branchreturn 0;}
Erklärung
1
if constexpr (std::is_floating_point_v<T>)
Wertet die Bedingung basierend auf dem Template-Typ bereits zur Kompilierzeit aus.
2
std::cout << "Processing float: " << val << std::endl;
Diese Zeile wird nur in das Binary kompiliert, wenn T ein Fließkommatyp ist.