Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't this std::find compare these objects

Tags:

c++

std

c++11

Usually when I do an std::find I'll put a predicate as the third argument, but this time I thought I'd do it differently, I don't understand why it doesn't work.

#include <iostream>
#include <vector>
#include <algorithm>

struct RenderJob
{
    RenderJob() {};
    int renderJob_ID;
    bool operator==(RenderJob& rhs) { return rhs.renderJob_ID == this->renderJob_ID; }
};

int main()
{
    RenderJob foo;
    RenderJob foo2;
    foo == foo2; // Works

    std::vector<RenderJob> renderJobs;

    std::find(renderJobs.begin(), renderJobs.end(), foo); // Doesn't work
}

binary "==" no operator found which takes a left-handed operand of type RenderJob (or there is no acceptable conversion)

Edit:: Well thanks for the answers. Here are some examples of why it fails

    RenderJob foo;
    RenderJob foo2;
    foo == foo2; // Works

    std::vector<RenderJob> renderJobs;

    std::vector<RenderJob>::const_iterator constit = renderJobs.begin();

    *constit == foo2;  // Doesn't work

Even simpler as an illustration:

 const RenderJob* pToRenderJob;

*pToRenderJob == foo2;  // This fails because the pointed to 
                        // object is const, and cannot call the 
                        // operator== function because the actual function
                        // definition is not const. 

If it were the other way around:

foo2 == *pToRenderJob; // This would fail because the 
                        // operator==(RenderJob&) the actual argument 
                        // is not const. Very subtle rules
like image 208
Zebrafish Avatar asked Sep 27 '17 04:09

Zebrafish


1 Answers

You left your const qualifiers off.

bool operator==(const RenderJob& rhs) const { ... }
like image 127
Dúthomhas Avatar answered Oct 05 '22 23:10

Dúthomhas