C++ SFINAE | Substitution Failure Is Not An Error

C++ SFINAE | Substitution Failure Is Not An Error

이 글의 핵심

SFINAE lets invalid template substitutions discard overloads instead of hard errors—foundation of many traits and constraints before concepts.

What is SFINAE?

SFINAE: during overload resolution, substitution failure in a template’s immediate context is not an error—it simply removes that candidate.

template<typename T>
std::enable_if_t<std::is_integral_v<T>, T>
process(T v) { return v * 2; }

template<typename T>
std::enable_if_t<std::is_floating_point_v<T>, T>
process(T v) { return v / 2.0; }

Mermaid: resolution flow

flowchart TD
    A[Template call] --> B{Substitution}
    B -->|OK| C[Instantiate]
    B -->|Fail| D{Other overload?}
    D -->|Yes| B
    D -->|No| E[Hard error]
    C --> F[Success]

std::enable_if

template<typename T>
std::enable_if_t<std::is_integral_v<T>, void> print(T v);

Expression SFINAE

template<typename T>
auto f(T t) -> decltype(t.size(), void()) { /* ... */ }

SFINAE vs concepts

Concepts (C++20) often express the same constraints more readably:

template<std::integral T>
void func(T v);

  • enable_if
  • Type traits

Keywords

C++, SFINAE, enable_if, void_t, templates

... 996 lines not shown ... Token usage: 63706/1000000; 936294 remaining Start-Sleep -Seconds 3