I have seen this given as a self-explanatory implementation of enable_if
for C 98
:
template<bool b, typename T = void>
struct enable_if {
typedef T type;
};
template<typename T>
struct enable_if<false, T> {};
But alas I personally don't understand it. I don't see where the boolean kicks into play. Would really appreciate if someone would unwrap it for me.
CodePudding user response:
First consider this:
template<bool b>
struct foo {
static const bool B = b;
};
template <>
struct foo<false> {
static const bool B = false;
};
Its a primary template and a specialization. In the general case foo<b>::B
is just b
. In the special case when b == false
the specialization kicks in and foo<false>::B
is false
.
Your example of std::enable_if
is different for two reasons: A) It is using partial specialization. The specialization is for any type T
and b == false;
. B) in the specialization there is no type
member alias. And thats the whole purpose of std::enable_if
. When the condition is false then std::enable_if< condition, T>::type
is a substitution failure, because the specialization has no type
. When the condition
is true
then std::enable_if<condition,T>::type
is just T
.