shi*_*zou 3 c++ polymorphism operator-overloading shared-ptr c++11
我想std::find在一个shared_ptr抽象类的列表上使用,但我收到一个错误.有没有办法shared_ptr通过解除引用来比较两个std::find?
是否有可能让一个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
}
};
Run Code Online (Sandbox Code Playgroud)
错误C2679二进制'==':找不到哪个运算符采用'const Point'类型的右手操作数(或者没有可接受的转换)
注意:Point已经有了operator==.
find()旨在在迭代器范围内找到一个精确值.
您已经定义了a operator==来比较a A和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; });
Run Code Online (Sandbox Code Playgroud)