Patrick
Patrick

Reputation: 181

How to choose class's operator== overloading over the template operator==?

I have overloaded the operator== for several types, using both template and in-line class method. But when come to the reference of an object as the lhs. The template operator== overloading will be used. Why not the operator== overloaded in the class definition?

#include <iostream>

template <typename T0, typename T1>
bool operator==(const T0& lhs, const T1& rhs)
{
    std::cout << "Template == " << std::endl;
    return true;
}

struct Obj
{
    std::int32_t a;
    bool operator==(const Obj& rhs)
    {
        std::cout << "Obj == " << std::endl;
        return true;
    }
};

bool cmp(const Obj& obj) { return (obj == Obj{ 1 }); }

int main() {
    Obj a{ 2 };
    const Obj& b = a;
    cmp(a);
    cmp(b);
    a == b;
    b == a;
    return 0;
}

This code gives the following results:

Template ==
Template ==
Obj ==
Template ==

Is it possible to force the compiler using the overloading defined inside the class?

Upvotes: 1

Views: 120

Answers (1)

JeJo
JeJo

Reputation: 32722

Is it possible to force the compiler using the overloading defined inside the class?

Yes, simply make the operator== overload a const qualified function, so that it will act on the const object of Obj.

bool operator==(const Obj& rhs) const /* noexcept */
{
    std::cout << "Obj == \n";
    return a == rhs.a; // meaningful comparison
}

It chooses the template overload because it was the best match, which takes the const object.

As a side note, provide a meaningful comparison, something like above. See a demo

Upvotes: 2

Related Questions