我想在 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"
}
但它需要了解B
何时实施A
。有没有更好的办法?