我有一些遗留代码,而不是虚拟函数,而是使用kind
字段进行动态调度。它看起来像这样:
// Base struct shared by all subtypes
// Plain-old data; can't use virtual functions
struct POD
{
int kind;
int GetFoo();
int GetBar();
int GetBaz();
int GetXyzzy();
};
enum Kind { Kind_Derived1, Kind_Derived2, Kind_Derived3 /* , ... */ };
struct Derived1: POD
{
Derived1(): kind(Kind_Derived1) {}
int GetFoo();
int GetBar();
int GetBaz();
int GetXyzzy();
// ... plus other type-specific data and function members ...
};
struct Derived2: POD
{
Derived2(): kind(Kind_Derived2) {}
int GetFoo();
int GetBar();
int GetBaz();
int GetXyzzy();
// ... plus other type-specific data and function members ...
};
struct Derived3: POD
{
Derived3(): kind(Kind_Derived3) {}
int GetFoo();
int GetBar();
int GetBaz();
int GetXyzzy();
// ... plus other type-specific data and function members ...
};
// ... and so on for other derived classes ...
然后POD
类的函数成员是这样实现的:
int POD::GetFoo()
{
// Call kind-specific function
switch (kind)
{
case Kind_Derived1:
{
Derived1 *pDerived1 = static_cast<Derived1*>(this);
return pDerived1->GetFoo();
}
case Kind_Derived2:
{
Derived2 *pDerived2 = static_cast<Derived2*>(this);
return pDerived2->GetFoo();
}
case Kind_Derived3:
{
Derived3 *pDerived3 = static_cast<Derived3*>(this);
return pDerived3->GetFoo();
}
// ... and so on for other derived classes ...
default:
throw UnknownKindException(kind, "GetFoo");
}
}
POD::GetBar()
, POD::GetBaz()
,POD::GetXyzzy()
和其他成员的实现方式类似。
这个例子被简化了。实际的代码有十几种不同的子类型POD
和几十种方法。新的子类型POD
和新方法的添加非常频繁,因此每次我们这样做时,我们都必须更新所有这些switch
语句。
处理这种情况的典型方法是virtual
在POD
类中声明函数成员,但我们不能这样做,因为对象驻留在共享内存中。有很多代码依赖于这些结构是普通的旧数据,所以即使我能找到某种方法在共享内存对象中拥有虚函数,我也不想这样做。
因此,我正在寻找有关清理它的最佳方法的建议,以便所有关于如何调用子类型方法的知识都集中在一个地方,而不是分散在几十switch
个函数中的几十个语句中。
我想到的是,我可以创建某种包装 aPOD
并使用模板来最小化冗余的适配器类。但在我开始走这条路之前,我想知道其他人是如何处理这个问题的。