Blair Davidson
Blair Davidson

Reputation: 951

Why doesn't boost::enable_if cause an duplicate overloaded method compile error

I have got the code for enable_if working and it is allowing me to do some awesome stuff but I thought it would cause an error as my two methods shown below have the same method signature.

Anyone know why this is allowed?

#include <iostream>
#include <boost/type_traits>


template<bool T, class R = void>
struct enable_if{
   typedef R type;
};

template<class R>
struct enable_if<false, R>{

};

template<class T>
typename enable_if<boost::is_pod<T>::value >::type  print(const T& item){
   std::cout << "T is a pod with the value: " << item << std::endl;
}

template<class T>
typename enable_if<!(boost::is_pod<T>::value) >::type  print(const T& item){
   std::cout << "T is not a pod with the value: " << item << std::endl;
}

int main(int argc, const char * argv[])
{

   print(1);

   return 0;
}

Upvotes: 5

Views: 283

Answers (3)

aldo
aldo

Reputation: 2987

The two template functions do have the same signature as far as overload resolution goes. If they both were instantiated for any requested type, there would be an error.

However, when the enable_if succeeds for one and fails for the other, rather than produce a compilation error due to substitution failure, there is no error (SFINAE: "Substitution Failure Is Not An Error"), and the compiler simply ignores one of them as if it did not exist.

Thus only one of the two templates is instantiated for the given type, and there is no overload resolution error.

Upvotes: 0

Potatoswatter
Potatoswatter

Reputation: 137890

my two methods shown below have the same method signature

Look closely:

… enable_if< boost …

vs

… enable_if< ! boost …

They're not the same, they're opposites. If one is disabled, the other is enabled. That guarantees that exactly one is always visible to the caller. (Remember, enable_if renders the declaration completely invisible if the condition is false.)

Upvotes: 5

Jeff Paquette
Jeff Paquette

Reputation: 7127

The two methods differ by return type, e.g., by the template specialization of enable_if.

Upvotes: -1

Related Questions