laddu
laddu

Reputation: 9

error: no match for ‘operator<’ (operand types are ‘const A’ and ‘const A’)

#include <set>
#include <iostream>
using namespace std;

template<class T> 
class A 
{   
    public:
        A(T a = 0,T b =0): m_a(a),m_b(b) {}

        bool operator<(const A& lhs)
        {
            /* compare code */
        }
              
    private:
        T m_a;
        T m_b;   
};  

int main()   
{
    A<int> abc(2,3);

    set<A<int>> P2D;
    P2D.insert(abc);
    return 0;   
}

When I run this code, I get the following error

operand types are ‘const A’ and ‘const A’

If I declare the const keyword on the overload operator<:

bool operator<(const A& lhs) const
{
    /*  compare code */
}

It is not giving an error, but:

  1. Is there anything I'm missing here?
  2. Why is it giving an error if I don't declare the const keyword?

Upvotes: -1

Views: 10578

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598011

Your operator< needs to be const, because set operates on const objects internally.

Also, your operator< is not implemented correctly anyway. It is ignoring the members of the A object on the left-hand side of the comparison, it is only looking at the member of the A object on the right-hand side.

Try this instead:

#include <set>
#include <iostream>
using namespace std;

template<class T> 
class A 
{   
    public:
        A(T a = T(), T b = T()): m_a(a), m_b(b) {}

        bool operator<(const A& rhs) const
        {
            return ((m_a < rhs.m_a) ||
                    ((m_a == rhs.m_a) && (m_b < rhs.m_b))
                   );
            /* alternatively:
            return std::tie(m_a, m_b) < std::tie(rhs.m_a, rhs.m_b);
            */
        }
              
    private:
        T m_a;
        T m_b;   
};  

int main()   
{
    A<int> abc(2,3);

    set<A<int>> P2D;
    P2D.insert(abc);
    return 0;   
}

Online Demo

Upvotes: 5

Related Questions