When you have an if constexpr chain and want to trigger a compile‐time error if none of the conditions match, the usual approach is to use a static_assert in the final else branch. One common trick is to use a helper that is dependent on a template parameter (or some other dependent value) so that the static_assert only fails when that branch is actually compiled.
For example, suppose you have a template function where you want to select different code paths:
#include <iostream>
template <typename T>
inline constexpr bool always_false = false;
template <typename T>
void foo(T value) {
if constexpr(std::is_integral_v<T>) {
std::cout << "Handling integral value: " << value << "\n";
}
else if constexpr(std::is_floating_point_v<T>) {
std::cout << "Handling floating-point value: " << value << "\n";
}
else {
static_assert(always_false<T>, "Unsupported type provided to foo()");
}
}
int main() {
foo(42); // OK: Integral
foo(3.14); // OK: Floating-point
// foo("hello"); // Would trigger the static_assert error
return 0;
}
Explanation
-
Using if constexpr:
The if constexpr keyword allows the compiler to discard branches that are not taken. This is very useful in template code when you want to handle different types differently.
-
Error in the Final Else:
In the last else block, we want to signal an error if none of the conditions match. Writing a plain static_assert(false, "...") would fail unconditionally if that line is parsed even when not taken. To avoid that, we use a trick involving a dependent value.
-
The always_false Trick:
The helper always_false<T> is defined as a constexpr boolean that is always false, but it is dependent on the template parameter T. This dependency delay the evaluation of the static_assert until the branch is actually instantiated (i.e., when that branch is taken).
Thus, if T does not match any of the earlier conditions, the final branch is compiled and the static_assert fails, causing a compile‐time error with a custom message.
-
C++20 Considerations:
In C++20 you can still use this technique. It is fully supported and is one of the idioms for compile-time dispatch when using if constexpr.
Using this pattern, you enforce that only specific types are accepted in your template function, and if an unsupported type is used, the compiler will display your custom error message.
Feel free to adjust the error message and conditions to suit your needs!