我有一个函数,我无法轻易更改的签名或调用者,它获取对结构的引用。这个结构是一个基类,但是根据在这个函数中发现的东西,结构被确定为一个继承类型并被这样操作。之后,这些数据将根据我们在此处设置的方式进行适当的动态广播。
struct Base {
int baseMember;
}
struct Derived : public Base {
int derivedMember;
}
enum EvtType {
EVT_A,
EVT_B
}
void handleEvent(Base& data) {
data.baseMember++; //adjust the common member
switch (getEventType()) // some static returning EvtType
{
case EVT_A:
// I can instatiate this as required, setting baseMember in a constructor
// or something
Derived derivedInst;
// and now i can set the derived members as needed
derivedInst.derivedMember += 56; // this is just what happens with EVT_As
// FIXME: but how do I get this object into the data parameter?
break;
case EVT_B:
// do it differently, but the same idea
break;
}
//handle other event types
}
这可能与reinterpret_cast
类似,即使传入引用的对象可能已被其他人分配为Base
吗?
此外,根据交换机中案例的内容,考虑到我无法扩展{{EvtType
以设置正确的派生类,是否有更整洁的方法来设置映射1}}或Derived
类。