我想使用 std::find
在 shared_ptr
的列表中一个抽象类,但我收到一个错误。有没有办法比较两个 shared_ptr
通过在 std::find
中取消引用它们?
有没有可能交个 friend operator==
重载 shared_ptr<A>
?
最小的例子:
#include "point.h"
#include <list>
#include <algorithm>
#include <memory>
using namespace std;
class A {
protected:
Point loc;
public:
virtual void foo() = 0;
virtual bool operator==(const Point& rhs) const = 0;
};
class B: public A {
virtual void foo() override{}
virtual bool operator==(const Point& rhs) const override {
return rhs == loc;
}
};
class C {
list<shared_ptr<A>> l;
void bar(Point & p) {
const auto & f = find(l.begin(), l.end(), p); //<-- error is from here
}
};
Error C2679 binary '==': no operator found which takes a right-hand operand of type 'const Point' (or there is no acceptable conversion)
备注:Point
已经有 operator==
.
最佳答案
问题:
find()
旨在在迭代器范围内找到一个精确的值。
您已经定义了一个 operator==
来比较一个 A
和一个 Point
。但是您的列表不包含 A
对象,而是包含指向 A
对象的共享指针。不幸的是,将共享指针与 Point 进行比较并没有定义。这种不匹配会导致您报告的错误。
解决方案:
一个简单的解决方案是使用 find_if()
而不是 find()
:它不寻找精确值,而是寻找谓词变为真:
const auto & f = find_if(l.begin(), l.end(),[p](shared_ptr<A> &a){ return *a==p; });
关于c++ - Operator== 抽象类和 shared_ptr 的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34662996/