【问题标题】:C++ "interfaces" and derived type parameter in member methods成员方法中的 C++“接口”和派生类型参数
【发布时间】:2011-11-07 07:11:41
【问题描述】:

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

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) { ... }
};

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

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

我考虑过在 bar1 和 bar2 中将函数签名更改为 foo const &,然后在函数内部执行 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
        }
    }
}

这感觉很乱。

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

【问题讨论】:

  • 在代码中显示operator= 在文本operator==.. 你想要哪一个?
  • 感谢您发现我的错字。我的意思是operator==

标签: c++ inheritance


【解决方案1】:

您可以使用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)
    {

    }
};

【讨论】:

  • 我不认为静态继承适合这个 - 有很多缺点,例如 bar1bar2 是从不同的类派生的。
  • 这是强制我想在 C++ 中做的普遍接受的方式吗?
  • 看看Wikipedia。有一个很好的解释。
  • 你打错了,应该是 '==' 而不是单个 '='
  • @AndersK。是的,我知道。谢谢,这是为了解释。我阅读了上面的 cmets。
【解决方案2】:

那是因为您没有覆盖那些确切的方法。

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

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

应该改为

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

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

你可以走了。你应该阅读更多关于polymorphism

【讨论】:

  • 但这不是一个好主意:想象一下bar1 = bar2。使用您的解决方案,这个编译但不是正确的解决方案。
  • 是的,但是在某些情况下 bar1 = bar2 是正确的方法。此外,可以通过枚举对象类型来处理它,如果它们不匹配则返回 false,但在这种情况下,我猜你的解决方案更优雅,更“C++ 方式”。
  • 这是我在我的问题中写的。我说我很想将函数签名更改为operator==(foo const &amp;),然后在代码中执行dynamic_cast 以确保类型匹配。我正在寻找更好的解决方案。
  • 假设你在谈论'bool operator=='那么这个解决方案对我来说似乎是正确的。我认为多态检查相等性没有任何问题。顺便说一句,相等运算符可以是“const”方法。
  • @juanchopanza 我尽量避免使用dynamic_cast
猜你喜欢
  • 2018-08-09
  • 2010-12-12
  • 2017-11-08
  • 2011-09-24
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多