Search code examples
c++templatesconstexprif-constexpr

constexpr switch statements in C++


Do we have a switch constexpr support in C++?

For context, we all know that we have if constexpr for compile-time if statements. Those if-statements will have very low overhead as compiler will evaluate them at compile time. We (or in particular I) use them when we do template specializations.

I was wondering if we have the same thing for switch or not. I am interested in using a switch statement instead of long if constexpr list with the same run-time overhead.

Example:

Considering this code:

template <int OP>
int mul(int in) {
  if constexpr (OP == 1) {
    return in * 2;
  } else if constexpr (OP == 2) {
    return in * 3;
  } else {
    return in * 4;
  }
}

Is the following code equivalent to the above code, compilation-wise?

template <int OP>
int mul(int in) {
  switch(OP) {
    case 1:
      return in * 2;
    case 2:
      return in * 3;
    default:
      return in * 4;
  }
}

This is a Godbolt link to above examples link. The link, somehow, confirms that what I wrote above are equivalent (in terms of the final compilation artifacts). But, I am still interested in a formal confirmation from C++ Spec.


Solution

  • You're misunderstanding what if constexpr is for. It's not an optimization enabler, as you clearly saw yourself the compiler will optimize your ifs all the same.

    Instead, what if constexpr provides is the ability to write invalid C++ code (parseable but not well-formed) that is only valid in its own branch (for example, if you're testing for a templated type), but not valid overall.