I'm trying to check if a class has a method operator==. I found a solution with SFINAE here and it's working fine with the class I make.
It looks like this :
template <typename T>
class comparable
{
typedef char one;
typedef long two;
template <typename C> static one test( typeof(&C::operator==) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
But, when I try :
std::cout << comparable<int>::value << std::endl;
Then it returns false while I was expecting it to return true. Why is this ?
int is not a class-type and has no member operator==, which is what you check for with your &C::operator==. Thus, the test yields a "no". As others correctly pointed out, your test would also be negative for classes with only a non-member operator==.
How to correctly check whether an operator== exists has been asked here:
How to check whether operator== exists?
Your immediate approach is flawed (or incomplete) for at least two fundamental reasons.
Firstly, your method checks whether class C has a member named operator ==. Non-class types will not pass this test, since they have no members whatsoever. And int is a non-class type.
Secondly, this approach by itself does not detect classes for which operator == is implemented as a standalone function. For example, your test will say that std::string has no == operator. It is true that std::string has no such member, yet you can compare std::string's for equality using the standalone operator ==. So, even if int somehow were a class type, it still does not mean that it would implement operator == as a member function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With