C++"接口"和成员方法中的派生类型参数

ach*_*how 2 c++ inheritance

我正在尝试做这样的事情:

class foo {
    virtual void bool operator==(foo const & rhs) = 0;
};

class bar1 : public foo {
    bool operator==(bar1 const & rhs) { ... }
};

class bar2 : public foo {
    bool operator==(bar2 const & rhs) { ... }
};
Run Code Online (Sandbox Code Playgroud)

也就是说,我想指出实现foo接口的所有类必须operator==为其自己的派生类实现该方法.

但是,编译器抱怨bar1和bar2仍然是抽象类,因为它们还没有实现operator==(foo const &).

我已经考虑过将foo const &bar1和bar2中的函数签名更改为然后dynamic_cast在函数内部执行,但这看起来很乱:

class bar1 : public foo {
    bool operator==(foo const & rhs) {
        const bar1 * casted_rhs = dynamic_cast<const bar1 *>(&rhs);
        if (casted_rhs == NULL) {
            // not a bar1
            return false;
        } else {
            // go through rhs and this object and find out if they're equal
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这感觉很乱.

必须有更好的方法来做到这一点.

Tio*_*epe 5

您可以使用CRTP模式来强制这种情况.通过这种方式,模板基类强制operator==在派生类中实现:

template <typename T>
class foo {
    bool operator==(const T & rhs)
    {
        return static_cast<T>(*this).operator==(static_cast<T>(rhs));
    }
};

class bar1 : public foo<bar1> {
    bool operator==(const bar1  & rhs)
    {
    }
};

class bar2 : public foo<bar2> {
    bool operator==(const bar2 & rhs)
    {

    }
};
Run Code Online (Sandbox Code Playgroud)