Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

SFINAE — substitution failure versus a compilation error

SFINAE allows a template overload to be discarded when argument substitution produces an invalid type or expression in the immediate context. It does not hide arbitrary template errors.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

template<class T>
auto probe(const T& x) -> decltype(x.size(), bool{});
bool probe(...);

SFINAE means “Substitution Failure Is Not An Error”. When template argument substitution fails in the immediate context, the function specialization is not added to the overload candidate set. If no suitable candidate remains, the call is still invalid.

In the example, decltype(x.size(), bool{}) checks whether x.size() is valid without evaluating it and yields the type bool. For Sized, the template is selected; for int, substitution fails and probe(...) is selected.

The boundary matters: errors in a function body or a separately instantiated template are not protected by SFINAE. Merely moving a check into the function body does not safely discard an overload.

Examples

#include <iostream>

struct Sized {
    int size() const { return 3; }
};

template<class T>
auto probe(const T& x) -> decltype(x.size(), bool{}) {
    return true;
}

bool probe(...) {
    return false;
}

int main() {
    std::cout << std::boolalpha;
    std::cout << probe(Sized{}) << '\n';
    std::cout << probe(42) << '\n';
}

Result

true
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources