如何解决双重调度,不了解整个层次结构
| 我想在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的知识。有没有更好的办法?
解决方法
由于派生类仅需要检测参数类型是否与对象类型匹配,因此您可以使用直接检查。
virtual void foo( base *argument_base ) {
if ( derived *argument = dynamic_cast< derived * >( argument_base ) ) {
argument->something = pair_match_foo;
} else {
base_class::foo( argument_base );
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。