Jerry
Jerry

Reputation: 23

the return of function "if constexpr" and "else if constexpr"

I'm the beginner with C++. Could some one explain the output after compile process function. Thanks a lot.

  template <typename T>
  auto process(T arg)
  {
    // 4. With constexpr if, to enable the compiler to generate different code based on the type the template is instantiated with:
    if constexpr (std::is_same<T, bool>::value)
      return !arg;
    else if constexpr (std::is_integral<T>::value)
      return -arg;
    else if constexpr (std::is_floating_point<T>::value)
      return std::abs(arg);
    else
      return arg;
  }

int main(){
...
{
      auto v1 = process(false); // true
      auto v2 = process(42);    // -42
      auto v3 = process(-42.0); // 42.0
      auto v4 = process("42"s); // "42"
}
...
    return 0;
}

what's the real code compiler for process() is generated after we call above code in main function.

Upvotes: 1

Views: 321

Answers (1)

ruakh
ruakh

Reputation: 183201

what's the real code compiler for process() is generated after we call above code in main function.

process() is not a function, and no compiled version of it is produced (at least in typical implementations); rather, your program produces four separate functions, namely process<bool>, process<int>, process<double>, and process<std::string>, each of which has its own compiled version.

And that's not specific to if constexpr — it's just how templates work in general in C++.

Those compiled versions can completely omit the branches of the if statement that don't hold for the type argument; so, for example, process<bool> is as if it were defined like this:

template<>
bool process<bool>(bool arg)
{
    return !arg;
}

Upvotes: 4

Related Questions