Example of if constexpr
The below example demonstrates the use of if constexpr.
C++
// C++ program to demonstrate the use of if constexpr to // print the type of value given #include <iostream> using namespace std; // function to check for integar value template < typename C> void printInfo( const C& value) { // if the value is not integer, the if block will be // discarded if constexpr (is_integral_v<C>) { cout << "Integer Value " << value << endl; } // if the value is integer, the else block will be // discarded else { cout << "Non-Integer value:" << value << endl; } } // driver code int main() { printInfo(10); printInfo(3.15); } |
Output
Integer Value 10
Non-Integer value:3.15
Explanation: In the above example template function printInfo takes a template parameter C, and allows it to work with various data types. using if constexpr statement it checks at compile time if C is an integral type using is_integral_v<C>.
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.