CKTIS / C++
std::enable_if and std::enable_if_t — conditionally exposing a type
std::enable_if exposes a type only when a compile-time condition is true. The std::enable_if_t alias shortens the spelling; in an appropriate substitution context, it lets SFINAE remove candidates from overload resolution.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <type_traits>
template<bool B, class T = void> struct enable_if;
template<bool B, class T = void>
using enable_if_t = typename enable_if<B, T>::type;
// Usage:
// typename std::enable_if<condition, Result>::type
// std::enable_if_t<condition, Result>std::enable_if<B, T> from <type_traits> is a class template. When the constant condition B is true, its member type denotes T; when it is false, there is no member type. The default T is void. This is not a conditional statement executed at runtime.
std::enable_if_t<B, T> is an alias for the type typename std::enable_if<B, T>::type, not a separate class or Boolean value. With B == false, the alias does not denote a type — it does not automatically become void.
If the missing type causes substitution failure in the immediate context of a function template declaration, SFINAE applies: the candidate is removed rather than making the entire program fail to compile. This does not suppress arbitrary errors: using std::enable_if_t<false, int> outside such a context, or an error in an instantiated function body, can cause a compilation error.
In the example, the dependent return type enables the classify template for integral types. For 42, it wins over the ... overload; for 3.5, substitution fails and the fallback overload remains. The static_assert checks that both spellings denote the same type for a true condition.
Examples
#include <iostream>
#include <type_traits>
template<class T>
constexpr std::enable_if_t<std::is_integral_v<T>, const char*>
classify(T) {
return "integral";
}
constexpr const char* classify(...) {
return "other";
}
static_assert(std::is_same_v<
typename std::enable_if<true, int>::type,
std::enable_if_t<true, int>>);
int main() {
std::cout << classify(42) << '\n';
std::cout << classify(3.5) << '\n';
}
Result
integral other
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.