在C++ 11中根据派生类`operator ==`定义基类`operator ==`?

And*_*zos 8 c++ c++11

假设我有一个类型层次结构:

struct B { ... };

struct D1 : B { ... };
struct D2 : B { ... };
...
struct Dn : B { ... };
Run Code Online (Sandbox Code Playgroud)

每个Di都有自己的operator==定义:

struct Di : B
{
    bool operator==(const Di&) const { ... }
    ...
};
Run Code Online (Sandbox Code Playgroud)

我现在想要定义B,operator==这样:

struct B
{
    bool operator==(const B& that) const
    {
        // psuedo-code
        let i, such the dynamic type of this is Di
        let j, such the dynamic type of that is Dj

        if (i != j)
            return false;
        else
            return Di::operator==(this, that);
    }
 }
Run Code Online (Sandbox Code Playgroud)

组织这个或写这个的最好方法是什么?

(最终目标是我想使用值类型为B*的标准容器类型(例如std::set<B*>),但是Di::operator==s当它们来自同一派生类时使用自定义)

das*_*ght 6

在基类中定义受保护的虚函数.使其成为纯虚拟,以确保每个子类Di提供实现.该函数将知道强制转换的目标,因为它属于a Di.从==基类中的运算符调用该函数,并让它执行比较,如下所示:

struct B {
    bool operator==(const B& that) const {
        return this->equals(that);
    }
protected:
    virtual bool equals(const B& other) const=0;
};
struct D1 {
protected:
    virtual bool equals(const B& other) const {
        D1 *that = dynamic_cast<D1*>(&other);
        if (!that) return false;
        // Perform D1-specific comparison here.
        // You can use the == operator of D1, but you do not have to:
        return (*this) == (*that);
    }
};
Run Code Online (Sandbox Code Playgroud)

这种结构的作用是使==操作符虚拟的实现.

  • 具有非公共虚函数的@ user1131467和调用另一个公共非虚函数的公共非虚函数允许您在分派给特定类的东西之前做一些常见的工作(即:可以检查地址是否相等,只有当它们不是'时' t调用虚函数)Mikhail:如果你想删除语法重复,可以使用CRTP继承带有基类名称的operator ==. (2认同)