Is there an idiomatic approach in C++ for comparing polymorphic types for object equivalence?

前端 未结 1 524
攒了一身酷
攒了一身酷 2021-01-02 18:36

I have Base* pointers to two instances of a polymorphic type and I need to determine if the referenced objects are equivalent.

My current approach is to first use RT

相关标签:
1条回答
  • 2021-01-02 18:55

    For most of the derived classes, equivalent simply means that the member variables all the same value

    In C++ this is called 'equality' and is usually implemented using operator==(). In C++ you can override the meaning of operators, it is possible to write:

    MyType A;
    MyType B;
    if (A == B) {
        // do stuff
    }
    

    And have == call a custom function you define.

    I think you want to differentiate equality from identity which would mean the same object (i.e. same address).

    You can implement it as member function or free function (from wikipedia):

    bool T::operator ==(const T& b) const;
    bool operator ==(const T& a, const T& b);
    

    In your case you want to implement operator== for the base class, and then perform what you are doing.

    More concretely it would look like this:

    class MyBase
    {
        virtual ~MyBase(); // reminder on virtual destructor for RTTI
        // ...
    private:
        virtual bool is_equal(const MyBase& other);
    
        friend bool operator ==(const MyBase& a, const MyBase& b); 
    
        // ...    
    };
    
    bool operator ==(const MyBase& a, const MyBase& b)
    {
        // RTTI check
        if (typeid(a) != typeid(b))
            return false;
        // Invoke is_equal on derived types
        return a.is_equal(b);
    }
    
    
    class D1 : MyBase
    {
        virtual bool is_equal(const Base& other)
        {
            const D1& other_derived = dynamic_cast<const D1&>(other);
            // Now compare *this to other_derived
        }
    };
    
    class D2 : MyBase;
    { };
    
    
    D1 d1; D2 d2;
    bool equal = d1 == d2; // will call your operator and return false since
                           // RTTI will say the types are different
    
    0 讨论(0)
提交回复
热议问题