通常当我做一个std :: find时,我会把一个谓词作为第三个参数,但这次我认为我的方法不同,我不明白为什么它不起作用.
#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
}
Run Code Online (Sandbox Code Playgroud)
二进制"=="没有找到哪个运算符采用RenderJob类型的左手操作数(或者没有可接受的转换)
编辑::谢谢你的答案.以下是一些失败原因的例子
RenderJob foo;
RenderJob foo2;
foo == foo2; // Works
std::vector<RenderJob> renderJobs;
std::vector<RenderJob>::const_iterator constit = renderJobs.begin();
*constit == foo2; // Doesn't work
Run Code Online (Sandbox Code Playgroud)
更简单的说明:
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.
Run Code Online (Sandbox Code Playgroud)
如果是相反的方式:
foo2 == *pToRenderJob; // This would fail because the
// operator==(RenderJob&) the actual argument
// is not const. Very subtle rules
Run Code Online (Sandbox Code Playgroud)
Dút*_*has 14
你离开了你的const
资格赛.
bool operator==(const RenderJob& rhs) const { ... }
Run Code Online (Sandbox Code Playgroud)
在我看来像一个常量问题.尝试这样的事情:
bool operator==(RenderJob const &rhs) const {
return rhs.renderJob_ID == this->renderJob_ID;
}
Run Code Online (Sandbox Code Playgroud)
做比较你自己工作,因为你只是传递不是临时的普通对象,也不是const限定.有了std::find
,比较函数将(至少通常)接收对集合中对象的引用(通常是const限定的),因此它需要能够接收const限定引用.
归档时间: |
|
查看次数: |
872 次 |
最近记录: |