簡體   English   中英

運算符==重載抽象類和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==

問題:

find()旨在在迭代器范圍內找到一個精確

您已定義operator==以將APoint進行比較。 但是您的列表不包含A對象,而是共享指向A對象的指針。 不幸的是,將共享指針與Point進行比較並不是定義的。 這種不匹配會導致您報告的錯誤。

解:

一個簡單的解決方案是使用find_if()而不是find() :它不會查找精確值,但是謂詞變為true:

   const auto & f = find_if(l.begin(), l.end(),[p](shared_ptr<A> &a){ return *a==p; });

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM