No '==' operator found which takes a left-

2019-09-21 18:37发布

问题:

I was refactoring some of my code to use a structure instead of a single object.

As a result of this change I needed to add in the operator for '==' so my existing vector involving functions could correctly evaluate my objects stored in the vectors.

class IdentifyingClass; //forward declare class     
Class ReturnData
{
public:
  IdentifyingClass* value;
  float  some_trivial_additional_data;

  bool operator==(const ReturnData& query_obj)
  {
    return value == query_obj.value;
  }

  bool operator==(const IdentifyingClass* query_obj)
  {
    return value == query_obj;
  }
}

All my existing code that relied on this class was functioning correctly. I thought it was an open and shut refactor.

Then I had use of it in a different place in a different solution in a specific edge case that used this class type. I was attempting to use this

IdentifyingClass* object;
const std::vector<ReturnData>& data_vector = GetDataFromPlace();
if(std::find(data_vector.begin(), data_vector.end(), object) != data_vector.end()))
{
  //do special action;
}

Now I was generating a vector '==' comparison error telling me I didn't have a left-hand '==' operand of "const ReturnData".

回答1:

I tried a few things while looking with bafflement as to why the operator wasn't const when clearly my parameters were handling const.

It got to the point where I changed my above code to use std::find_if and used a lambda as my predicate to resolve the code to the functionality I wanted.

The real issue was my operators were not marked const:

bool operator==(const ReturnData& query_obj) const
{
  return value == query_obj.value;
}

bool operator==(const IdentifyingClass* query_obj) const
{
  return value == query_obj;
}

The reason I have made this rather trivial issue into a stack overflow post is that other posts I have found similar to this only highlight other issues with those posts and not this specific case, which did take a little while to spot.

Top related posts of my issue:

Vector is of const objects

Typedef and namespace issue