c++ - 在 C++ 中一般比较继承层次结构中的对象

标签 c++ generics inheritance polymorphism generic-programming

我打算写一个这样的 multimap

std::multimap <key, base_ptr> mymap;

而且我希望能够存储从基类派生的许多派生类(例如 Der1Der2)的指针。

现在,当我试图将一个对象插入到映射中时,我首先在键上进行查找,然后我需要比较该对象是否是 EQUIVALENT(不必是同一个对象,因此不进行指针比较) 到那个位置的那个。因此,假设我重写了 == operator 或编写了某种比较函数。现在我想为此编写代码,这样当添加新的派生类时,我不必更改或添加任何内容。

所以我认为必须有一种通用的编写方法。但想不出一个。

我在想下面这样的事情

class Base
{
    virtual Base * get() { return this; }

    virtual bool isEqual(const Base& toObj) {
        ....
    }
}

class Der1
{
    Der1 * get() { return this; }

    bool isEqual(const Der1& toObj) {
        ....
    }
}

但这似乎也行不通。因为当我这样做时:

Base* bp1;
Base* bp2;
bp1->get()->isEqual(*(bp2->get()))

我看到对 get() 的调用确实像我预期的那样在派生类的 get() 中结束,但随后编译器会处理返回值作为 Base*。这很可能是因为它是运行时多态性。但我很难相信不会有一种优雅而明显的方法来做到这一点。

有人可以建议吗。

最佳答案

你可以尝试这样的事情:

class Base
{
    public:

    // derived classes must implement this.
    // the implementation is always the same code
    virtual type_info getType() const = 0;

    virtual bool isEqual(const Base& toObj) = 0;
}

class Der1 : Base
{
    public:
    type_info getType() const { return typeid (this); }

    bool isEqual(const Base& toObj)
    {
        if (this.getType() == toObj.getType())
        {
            // we have 2 instances of Der1!
            // do comparison here
        }
        else
        {
            // the other one is no Der1 => we are not equal
            return false;
        }
    }
}

class Der2 : Base
{
    public:
    type_info getType() const { return typeid (this); }

    bool isEqual(const Base& toObj)
    {
        if (this.getType() == toObj.getType())
        {
            // we have 2 instances of Der2!
            // do comparison here
        }
        else
        {
            // the other one is no Der1 => we are not equal
            return false;
        }
    }
}



void MyFunc()
{
    Base* bp1;
    Base* bp2;
    // ...
    // this should work now (although I have not tested it!)
    bool theyAreEqual = bp1->isEqual(*bp2);
}

关于c++ - 在 C++ 中一般比较继承层次结构中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21529062/

相关文章:

c++ - 具有多个文件夹的 Visual Studio 项目

r - R6 类的 S4 调度行为不一致

c# - Entity Framework TPC 外键关系

c++ - 模板函数,如何发送不同的结构并根据类型创建 if/else 语句?

c++ - 合并排序在 C++ 中不起作用

c++ - Linux 上的 GMP(MPIR) 链接器错误

C# 通用接口(interface)

lambda - 如何从泛型、clazz 和接口(interface)中获取 Java 8 Lambda?

java - Jackson - 使用泛型类反序列化

c++ - 调用基类函数时强制类名?