Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

boost

sfinae

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;
}
like image 459
Blair Davidson Avatar asked Oct 08 '22 00:10

Blair Davidson


1 Answers

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.)

like image 51
Potatoswatter Avatar answered Oct 12 '22 11:10

Potatoswatter