Implementing comparisons using a common interface in C ++

Let's say I'm working on a library that works with items like Item. The main entry point is the class, for example:

class Worker
{
private:
  SomeContainer _c;
public:
    void add( const Item &i );
    void doSomething();
};

The method doSomething()considers the added elements, compares them, etc. and does something with them. Therefore, the class Item is required operator==.

Now I want to use this library in different environments, and in each environment the implementation of the Item class is different. Therefore, an element requires a virtual comparison function:

class Item
{
protected:
    virtual bool _equals( Item &other ) = 0;
public:
    bool operator==( Item &other ) { return _equals( other ); };
};

And each environment has its own element implementation. The library only knows about the Item class, and certain element classes are defined and implemented in platform applications using the library. In environment A, it could be:

class AItem: public Item
{
private:
    bool _equals( Item &other );
    std::string _member;
...
};

and in environment B:

class BItem: public Item
{
private:
    bool _equals( Item &other );
    int _member;
...
};

? _equals Item, other .

, , , :

bool AItem::_equals( Item &other )
{
    return this->_member == static_cast<AItem &>(other)._member;
}

, , , , , .

, , :

  • dynamic_cast.
  • RTTI, Item, . , , other . .
  • #define . , .
  • .

, . , . ?

+3
2
  • , Item , ? ( ) . , SomeContainer , .

  • , , " " ( " ++", ). . . Item. ( , , ).

: :

class ItemA;
class ItemB;

class Item
{
public:
    virtual bool equal(Item const&) const = 0;
protected:
    virtual bool doesEqual(ItemA const*) const { return false; }
    virtual bool doesEqual(ItemB const*) const { return false; }
};

class ItemA: public Item
{
public:
    virtual bool equal(Item const& other) const
    {
        return other.doesEqual(this);
    }
protected:
    virtual bool doesEqual(ItemA const* other) {
        return do_the_check;
    }
};

class ItemB: public Item
{
public:
    virtual bool equal(Item const& other) const
    {
        return other.doesEqual(this);
    }
protected:
    virtual bool doesEqual(ItemB const* other) {
        return do_the_check;
    }
};

bool operator==(Item const& lhs, Item const& rhs)
{
    return lhs.equal(rhs);
}
+4

Imho, . : A , B.

, , .

, : a b, b a. , , . . , .

0

Source: https://habr.com/ru/post/1713571/


All Articles