Syntax of if constexpr
if constexpr (condition) { // Code executed only if condition is true at compile time } else { // Code executed only if condition is false at compile time }
Here, the condition is a constant expression to be executed at compile time. If the given condition results in true then the code inside the first block is included and if the condition results in false then the code inside the else block is included.
Note: The code inside the block which is not selected gets discarded during compilation.
if constexpr in C++ 17
In C++17, if constexpr
feature was introduced to allow compile-time branching based on constant expressions. Unlike regular if
statements, which are evaluated at runtime, the if constexpr allows the compiler to discard branches of code that do not apply. It means only the branch of code for which the condition is true is compiled and other code branch is discarded during compilation.