C++ 17 vs. C++ 14 — if-constexpr

We are excited to see that if-constexpr made it to C++ 17. You can try it yourself using the current trunk of clang.

In this blog-post we revisit some C++ 14 code and try to use the new feature.

Not having if-constexpr at your disposal, you often need to resort to elaborate meta-programming techniques, utilising template pattern-matching, overload-resolution and SFINAE.

Example 1 — getting the nth-arg

Many template meta-programs operate on variadic-type-lists. In C++ 14, getting the nth-type of an argument lists is often implemented the following way:

C++ 17 makes this slightly more intuitive:

Example 2 — API — shimming

Sometimes you want to support an alternative API. C++ 14 provides an easy way to check if an object can be used in a certain way:

Implementing custom behaviour in C++ 14 can be done like this:


This is very convenient as code that belongs semantically together is not scattered across multiple functions. Furthermore, you can even define lambdas containing if-constexpr.

Example 3 — Compile-time algorithm-picking

Often you need to find the best algorithm based on a set on rules and properties of a type. There are many solutions. For instance, the STL uses TypeTags to pick the right algorithm for some given iterators.

However, once you have more complex rules, you might need a more powerful solution — SFINAE:

C++ 14:

With C++ 17 you can describe these rules with less boilerplate and in a clearer way:

This is very practical as working with ifs is more intuitive than using a variety of language-features.

Refactoring meta-functions becomes as simple as ordinary code. With if-constexpr, worrying about ambiguous overloads and other unexpected complications is a thing of the past.

We will upgrade our compiler as soon as Clang 3.9 is stable.

C++ dev tools company. Find out more at https://github.com/LoopPerfect/buckaroo

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store