std::enable_if
| Defined in header <type_traits>
|
||
| template< bool B, class T = void > struct enable_if; |
(since C++11) | |
If B is true, std::enable_if has a public member typedef type, equal to T; otherwise, there is no member typedef.
This metafunction is a convenient way to leverage SFINAE to conditionally remove functions from overload resolution based on type traits and to provide separate function overloads and specializations for different type traits. std::enable_if can be used as an additional function argument (not applicable to operator overloads), as a return type (not applicable to constructors and destructors), or as a class template or function template parameter.
Member types
| Type | Definition |
type
|
either T or no such member, depending on the value of B
|
Helper types
| template< bool B, class T = void > using enable_if_t = typename enable_if<B,T>::type; |
(since C++14) | |
Possible implementation
template<bool B, class T = void> struct enable_if {}; template<class T> struct enable_if<true, T> { typedef T type; }; |
Notes
A common mistake is to declare two function templates that differ only in their default template arguments. This is illegal because default template arguments are not part of function template's signature, and declaring two different function templates with the same signature is illegal.
struct T { enum { int_t,float_t } m_type; template <typename Integer, typename = std::enable_if_t<std::is_integral<Integer>::value> > T(Integer) : m_type(int_t) {} template <typename Floating, typename = std::enable_if_t<std::is_floating_point<Floating>::value> > T(Floating) : m_type(float_t) {} // error: cannot overload };