Enabling SFINAE with the enable_if Type Trait

Learn to use the enable_if type trait to achieve SFINAE in C++ metaprogramming.

The C++ standard library is a family of sublibraries. One of these is the type support library. This library defines types such as std::size_t, std::nullptr_t, and std::byte, runtime type identification support with classes such as std::type_info, as well as a collection of type traits. There are two categories of type traits:

  • Type traits that enable us to query properties of types at compile-time.

  • Type traits that enable us to perform type transformations at compile-time (such as adding or removing the const qualifier, or adding or removing a pointer or reference from a type). These type traits are also called metafunctions.

SFINAE in function overloads

One type trait from the second category is std::enable_if. This is used to enable SFINAE and remove candidates from a function’s overload set. A possible implementation is the following:

Get hands-on with 1200+ tech skills courses.