In a recent question, the usage of std::enable_if as a conditional return type was discussed. While the first usage was clear, the second, which included a seemingly meaningless assignment to std::enable_if, remained puzzling.
Unlocking the Concept
To unravel the mystery, we must delve into the definition of std::enable_if:
template<bool Cond, class T = void> struct enable_if {}; template<class T> struct enable_if<true, T> { typedef T type; };
The key lies in the fact that typedef T type is only defined when bool Cond is true.
Applying to the Example
With this understanding in hand, let's revisit the code:
template<typename T> typename std::enable_if<std::numeric_limits<T>::is_integer, void>::type foo(const T &bar) { isInt(bar); }
Here, std::enable_if is used to define the return type of the foo function. If T is an integer, the return type will be void; otherwise, the function will not compile.
The Role of Defaulting
In the second example:
template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> void foo(const T& bar) { isInt(); }
The = 0 default parameter ensures that both options can be called with foo
Evolving the Understanding
In C 14, the std::enable_if_t type is introduced, which should be used in place of the typedef form. This results in a more concise return type:
std::enable_if_t<std::numeric_limits<T>::is_integer>
The above is the detailed content of Why is there a Seemingly Meaningless Assignment to std::enable_if in C Templates?. For more information, please follow other related articles on the PHP Chinese website!