请考虑以下(简化的)类层次结构和处理功能:
struct msgBase
{
virtual int msgType() const=0;
};
struct msgType1:public msgBase
{
virtual int msgType() const{return 1;}
};
struct msgType2:public msgBase
{
virtual int msgType() const {return 2;}
};
void process(const msgType1& mt1)
{
// processing for message type 1
}
void process(const msgType2& mt2)
{
// processing for message type 2
}
void process(const msgBase& mbase)
{
switch(mbase.msgType())
{
case 1:
process(static_cast<const msgType1&>(mbase));
break;
case 2:
process(static_cast<const msgType2&>(mbase));
break;
}
}
在集成设计中,msgBase 将被赋予虚拟“过程”方法,以避免需要迭代类型。
如果不可能或不需要修改任何类,是否有迭代类型的替代方法?
我已经尝试了装饰器/工厂模式,其中类的并行层次结构封装了给定的类,并实现了必要的虚拟函数,但这会导致大量的样板文件,并且工厂函数仍然需要迭代类型!
我可以用一系列 dyamic_cast 替换 switch 语句,但这仍然留下相同的弱点。
最佳答案
根据 Simon 的要求,我所说的 CRTP 的含义如下:
typedef <class Derived>
struct msgBase
{
virtual void process(){
// redirect the call to the derived class's process()
static_cast<Derived*>(this) -> process();
};
struct msgType1:public msgBase<msgType1>
{
void process(){
// process as per type-1
}
};
struct msgType2:public msgBase<msgType1>
{
void process(){
// process as per type-2
}
};
这里发生了什么?考虑这种情况:
msgBase* msg = new msgType1();
msg->process();
通常(没有 CRTP)这只会调用 msgBase::process()
。但现在,msgBase
“知道”使用模板的msgType1
,因此它在编译时被重定向到msgType1::process
/em>。
关于由 小码哥发布于 2019-11-08 09:00:00 c++design: avoid iterating over types with an existing class hierarchy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074078/