Home > Backend Development > C++ > body text

Why Doesn't `if constexpr` Work in Non-Templated Functions in C 17?

Barbara Streisand
Release: 2024-11-06 19:01:03
Original
493 people have browsed it

Why Doesn't `if constexpr` Work in Non-Templated Functions in C  17?

if constexpr Does Not Behave As Expected in Non-Templated Functions in C 17

In C 17, the if constexpr statement allows for conditional compilation based on compile-time constant expressions. However, when attempting to use this feature in a non-templated function, unexpected compilation errors may occur.

Consider the following code snippet:

<code class="cpp">#include <iostream>
#include <type_traits>

int main()
{
  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>
Copy after login

When compiling this code, an error will occur on the line attempting to dereference 'value' within the if constexpr statement. This is because if constexpr is not supported in non-templated functions.

Why Only Templates?

This behavior is by design. if constexpr is intended to prevent instantiation of invalid template code based on specific specializations. In the example provided, the non-templated function checks whether 'value' is a pointer using std::is_pointer_v. However, if the condition is false, the compiler still attempts to dereference the integer 'value', which is invalid.

Solution

To use if constexpr in non-templated contexts, consider wrapping the code in a template function or using a macro that will behave differently at compile time. For example:

<code class="cpp">#include <iostream>
#include <type_traits>

template<typename T>
void print(T value)
{
  if constexpr (std::is_pointer_v<T>)
    std::cout << "Ptr to " << *value << std::endl;
  else
    std::cout << "Ref to " << value << std::endl;
}

int main()
{
  auto n = 1000;
  print(n);

  int *ptr = &n;
  print(ptr);
}</code>
Copy after login

In this case, the print function is templated, so if constexpr behavior is correctly applied based on the template parameter.

The above is the detailed content of Why Doesn't `if constexpr` Work in Non-Templated Functions in C 17?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!