cpp / expert
Snippet
Type-Based Branching Logic
Advanced control flow utilizing 'if constexpr' for compile-time branching. This prevents the instantiation of invalid code paths, allowing generic code to handle disparate types like primitives and objects with specific methods.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
template <typename T>auto process_input(T&& val) {if constexpr (std::is_integral_v<std::decay_t<T>>) {return val * 2;} else if constexpr (std::is_floating_point_v<std::decay_t<T>>) {return val / 2.0;} else if constexpr (requires { val.length(); }) {return val.length();} else {static_assert(false, "Unsupported type passed to process_input");}}
Breakdown
1
if constexpr (std::is_integral_v<std::decay_t<T>>)
Checks at compile time if the decayed type is an integer, discarding other branches entirely.
2
else if constexpr (requires { val.length(); })
Uses a C++20 requirement expression (Concept syntax) to check if the object has a length() method before calling it.