双重调度,不了解整个层次结构
|
我想在C ++中实现以下功能:
我想拥有一堆单个类的子类,并且能够调用一个函数,该函数需要一对这些类型的对象。假设有一个通用的实现被称为混合类型或基本类型,而一个专门的实现则被调用,如果两个相同派生类型的对象被用作参数。
据我所知,这是双重调度的经典应用。但是,我有以下限制:
必须有可能从现有的类派生新的类,并为这些新的类添加新的对函数,而无需更改现有的类,例如在外部库中。
我在上一个问题中提出的方法是错误的,并且那里提出的解决方案仅适用于编写基类时已知的类型。
关于如何实施此建议?那有可能吗?
更新:代码说出一千多个单词。以下方法有效:
#include <iostream>
class B;
class A
{
public:
virtual void PostCompose(A* other)
{
other->PreCompose(this);
}
virtual void PreCompose(A* other)
{
std::cout << \"Precomposing with an A object\" << std::endl;
}
virtual void PreCompose(B* other);
};
class B : public A
{
public:
using A::PreCompose;
virtual void PostCompose(A* other)
{
other->PreCompose(this);
}
virtual void PostCompose(B* other)
{
other->PreCompose(this);
}
virtual void PreCompose(B* other)
{
std::cout << \"Precomposing with a B object\" << std::endl;
}
};
void A::PreCompose(B* other)
{
PreCompose((A*)other);
}
int main()
{
B b;
A* p = &b;
p->PostCompose(p); // -> \"Precomposing with a B object\"
}
但是在实现A
时需要ѭ1的知识。有没有更好的办法?
没有找到相关结果
已邀请:
1 个回复
瓜唱鬼