0Pricing
C++ Academy · Lesson

enable_if Patterns

Constrain templates the classic way.

What Is enable_if?

std::enable_if is a small trait that conditionally defines a type member. When its condition is true the type exists; when false, the surrounding template is removed via SFINAE.

  • Lives in <type_traits>.
  • It is the classic tool for constraining templates.
#include <iostream>
#include <type_traits>

template <typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type
doubleIt(T v) { return v * 2; }

int main() {
    std::cout << doubleIt(21) << '\n';
    return 0;
}

How It Works

enable_if<Cond, T>::type is T only when Cond is true. If false, there is no type member, so the substitution fails.

#include <iostream>
#include <type_traits>

int main() {
    std::cout << std::boolalpha;
    std::cout << std::is_same<std::enable_if<true, int>::type, int>::value << '\n';
    return 0;
}

All lessons in this course

  1. Full Specialization
  2. Partial Specialization
  3. SFINAE
  4. enable_if Patterns
← Back to C++ Academy