由 小码哥发布于 2019-11-08 09:00:00 c++design: avoid iterating over types with an existing class hierarchy

标签 c++ polymorphism

请考虑以下(简化的)类层次结构和处理功能:

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/

相关文章:

c++ - 如何从另一个实例的类型动态实例化一个新实例? C++

c++ - 从 C++ 调用 awk 脚本在 "bozo :wait_for"停止

c++ - 为什么 MSVC 静态局部变量的线程安全初始化使用 TLS

c++ - 比较 std::list 中的两个连续元素

oop - 如何在没有代码冗余的情况下表示两个真正相似的结构?

c++ - 派生类映射

c++ - 如何在不重载纯虚函数的情况下将抽象类转换为普通类?

c++ - 如何编译#includes C++代码的C代码?

c++ - 从 Derived* 转换为 Base*&

c++ - 为什么以及何时使用多态性将基类指向 C++ 中的派生类