Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template class error with operator ==

Error:
error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const entry' (or there is no acceptable conversion)

The function:

template <class T, int maxSize>
int indexList<T, maxSize>::search(const T& target) const
{
    for (int i = 0; i < maxSize; i++)  
        if (elements[i] == target)   //ERROR???
            return i;       // target found at position i

    // target not found
    return -1;
}

indexList.h
indexList.cpp

Is this suppose to be an overloaded operator? Being a template class I am not sure I understand the error?

Solution- The overload function in the class now declared const:

//Operators
bool entry::operator == (const entry& dE)  const <--
{
    return (name ==dE.name);

}
like image 921
T.T.T. Avatar asked Apr 07 '09 15:04

T.T.T.


3 Answers

Start by reading the error text exactly as it is:

binary '==' : no operator found which takes a left-hand operand of type 'const entry'

It means it can't find any == operator that accepts an entry type as its left operand. This code isn't valid:

entry const e;
if (e == foo)

You've showed us the code for your list class, but that's not what the error is about. The error is about a lack of operators for the entry type, whatever that is. Either give the class an operator== function, or declare a standalone operator== function that accepts a const entry& as its first parameter.

struct entry {
  bool operator==(const entry& other) const;
};
// or
bool operator==(const entry& lhs, const entry& rhs);

I think the latter is the preferred style.

like image 108
Rob Kennedy Avatar answered Nov 14 '22 19:11

Rob Kennedy


The problem refers to the type T that is being used in this instance not having an operator== defined. I would guess from your question that this is a class 'entry'.

It might also be that the 'entry' class does not have the operator== defined correctly to take a const entry& as a parameter.

like image 27
dma Avatar answered Nov 14 '22 19:11

dma


This is likely "const poisoning", where your use of const in the declaration of your search function will force you to add const versions of all the downstream functions you call.

In a function declared const, the this pointer is considered const, which means that all the members you use through that pointer are considered const as well. If your operator == () for whatever type T you are specializing with doesn't explicitly specify const parameters, you will get this error.

If you can't ensure that all Ts you use will have the proper operator == () calls, I'd remove the const specifiers on the member function templates.

like image 2
mwigdahl Avatar answered Nov 14 '22 19:11

mwigdahl