if constexpr in C 17 Not Working in Non-Templated Functions
Introduction
The C 17 standard introduced the if constexpr construct, which allows for conditional execution based on constant expressions. However, it has been observed that if constexpr behavior differs when used in templated versus non-templated functions.
Problem
Consider the following non-templated function:
<code class="cpp">void print() { auto value = 100; if constexpr (std::is_pointer_v<decltype(value)>){ std::cout << "Ptr to " << *value << std::endl; // Error } else { std::cout << "Ref to " << value << std::endl; } }</code>
This code results in a compilation error because *value is invalid for the deduced type int.
Answer
This behavior is by design. In templated functions, if constexpr can avoid instantiating branches that are not valid for specific template specializations. However, in non-templated functions, if constexpr does not suppress compilation of the non-taken branch.
Both branches of the if constexpr statement are parsed and analyzed, even if the branch not taken is invalid. Therefore, in the above code, the compiler will attempt to evaluate *value for an int type, resulting in an error.
Conclusion
This distinction is important to understand when using if constexpr. In non-templated functions, it should only be used to check constant expressions that are guaranteed to be valid for all possible values of the input parameters.
The above is the detailed content of Why Doesn't `if constexpr` Work as Expected in Non-Templated C Functions?. For more information, please follow other related articles on the PHP Chinese website!