[英]accessing operator overloading of class which is wrapped by std::shared_ptr
[英]Operator== overloading of an abstract class and shared_ptr
我想在抽象類的shared_ptr
列表中使用std::find
,但是我收到了一個錯誤。 有沒有辦法比較兩個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
}
};
錯誤C2679二進制'==':找不到哪個運算符采用'const Point'類型的右手操作數(或者沒有可接受的轉換)
注意: Point
已經有operator==
。
std::find
可以實現為
template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value)
{
for (; first != last; ++first) {
if (*first == value) {
return first;
}
}
return last;
}
正如您所看到的,它是比較*first == value
,當使用find(l.begin(), l.end(), p)
時,它轉換為shared_ptr<A> == Point
。 因為它將使用shared_ptr<A>::operator==
你將使用std::find_if
並編寫一個自定義比較函數/函數,可以比較這兩種類型並將其傳遞給find
您可以在以下位置了解有關仿函數的更多信息: C ++ Functors及其用途
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.