← Back to list

Farewell SFINAE, welcome if constexpr

What is if constexpr?

Sireanu Roland · 2025-01-21 10:52 · 4 claps · 1.4 min read
#c #sfinae #constexpr
Open on Medium ↗

Farewell SFINAE, welcome if constexpr

What is if constexpr?

The if constexpr construct is a feature introduced in C++17 that allows compile-time branching. It provides a cleaner, more readable and easier to maintain alternative to SFINAE (Substitution Failure Is Not An Error).

Let’s take a toy example to showcase the capabilities of if constexpr. In order to compare two generic variables, we should take into account the specifics of each possible type. Although the variables are generic, you cannot compare floating points in the same way as you compare integers. Therefore, a compile-time branching is needed. Let’s see two options for this problem:

Taking a traditional approach, using SFINAE:

#include <cmath>
#include <limits>

template<typename T>
std::enable_if_t<std::is_floating_point_v<T>, bool> areEqual(T aOp1, T aOp2)
{
    return fabs(aOp1 - aOp2) < std::numeric_limits<T>::epsilon();
}

template<typename T>
std::enable_if_t<std::is_integral_v<T>, bool> areEqual(T aOp1, T aOp2)
{
    return aOp1 == aOp2;
}

Depending on the deduced type T, at compile time, a single implementation of areEqual function will be chosen.

Taking a modern approach, using if constexpr

template<typename T>
bool areEqualModernApproach(T aOp1, T aOp2)
{
    if constexpr(std::is_integral_v<T>)
        return aOp1 == aOp2;
    else if constexpr(std::is_floating_point_v<T>)
        return fabs(aOp1 - aOp2) < std::numeric_limits<T>::epsilon();
    else
        static_assert(false, "Unsupported type");
}

Compared to SFINAE (which requires a lot of boilerplate code), the logic in the if constexpr approach is contained within a single function template, and the intent is clearer because it reads sequentially rather than through overload resolution.

This last part is for the curious ones :-D

How does the code look like after the evaluation of if constexpr?

The conditional branch which doesn’t meet the compile time requirements is removed from the final implementation of areEqualModernApproach.

In conclusion, if constexpr provides an elegant way to insert branching points into the compilation process without the drawbacks associated with the SFINAE method.

For any feedback, questions, or thoughts, feel free to contact me on *LinkedIn or [Gmail](http://sireanu.roland@gmail.com/).*


메타데이터
post_id
d405b6ea7b41
slug
farewell-sfinae-welcome-if-constexpr-d405b6ea7b41
url
https://medium.com/@sireanu.roland/farewell-sfinae-welcome-if-constexpr-d405b6ea7b41
canonical_url
https://medium.com/@sireanu.roland/farewell-sfinae-welcome-if-constexpr-d405b6ea7b41
author_url
https://medium.com/@sireanu.roland
status
ok
fetched_at
2026-07-29 05:58:23