Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does int have an operator==

Tags:

c++

sfinae

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 ?

like image 384
Malcolm Avatar asked Feb 15 '16 22:02

Malcolm


2 Answers

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?

like image 51
Baum mit Augen Avatar answered Oct 13 '22 20:10

Baum mit Augen


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.

like image 31
AnT Avatar answered Oct 13 '22 19:10

AnT