This is the fourth part of the series “6 Useful New Features in C++17”, the first part can be found here.
If Statements with constexpr Condition
This is a feature that perhaps has its main use while working with templated classes and such, but there are other uses as well, e.g., together with variadic arguments. constexpr adds the ability to discard branches at compile time. You might argue that a compiler optimizes code to achieve the same behavior anyway, and of course, you are correct. However, using constexpr if guarantees that it is evaluated at compile time, and at the very least the code compiles faster.
I would like to show an example when one makes use of SFINAE, a situation where I think constexpr if is useful. What follows is a non-sensical code snippet using SFINAE and C++14 revision.
With the use of constexpr if in C++17 it can be written with only one function, like so:
I know which version I would like to work with.
These features are all fully supported by GCC, MSVC, and clang. Below follows a table showing which version enables support for each feature respectively.
For more a detailed matrix with more compilers and all features of C++17 listed, follow this link.
READ PART 5 “6 Useful New Features in C++17” HERE.
// Patrik Ingmarsson