c++ - 使用可重写的处理函数构建类层次结构

标签 c++ templates typelist

我目前正在尝试使用 C++ 模板自动构建类层次结构。最终结果是一个消息处理程序类,它为类型列表中给定的所有可能消息提供处理函数。

但是,当从该类层次结构继承并尝试实现处理函数以实际执行应用程序代码时,仅针对某些类型,C++ 不会从基类调用该函数。

以下是我要实现的最小且完整的示例。它无法编译,因为 C++ 提示没有找到 handle( const B& ) 的重载。

#include <iostream>
#include <typeinfo>

// Typelist.
struct None {};

template <class H, class T = None>
struct Typelist {
    typedef H Head;
    typedef T Tail;
};

template <class TL>
struct Handler : public Handler<typename TL::Tail> {
    using Handler<typename TL::Tail>::handle;

    virtual void handle( const typename TL::Head& obj ) {
        std::cout << "Not handled! " << typeid( typename TL::Head ).name() << std::endl;
    }
};

template <>
struct Handler<None> {
    virtual void handle() {}
};

struct A {};
struct B {};

typedef Typelist<A, Typelist<B> > MsgList;

struct MyHandler : Handler<MsgList> {
    void handle( const A& a ) {
        std::cout << "A!" << std::endl;
    }
};

int main() {
    MyHandler handler;

    A a;
    B b;

    handler.handle( a );
    handler.handle( b );
}

最佳答案

您需要使用您的句柄Handle<MsgList>在你的MyHandler

using Handler<MsgList>::handle;

现在它是隐藏的,不要重载名称 handleMyHandler类(class)。并考虑到 Handler 的代码,你知道这个:-)

关于c++ - 使用可重写的处理函数构建类层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931275/

相关文章:

c++ - 策略函数的非类型模板

c++ - C++ 中不熟悉的符号 [=]

c++ - 使用可变参数模板将嵌套类型列表转换为平面类型列表

c++ - 使用 OpenCV 2.4 在 MFC SDI View 或 Control 中加载图像

c++ - alloca() 在哪些情况下有用?

c++ - 从 Swift 中的泛型参数继承的替代方法

c++ - 基本类型列表功能

c++ - 类型列表的使用

c++ - std::map 的大小大于调试器中显示的元素数量

c++ - 'new' 关键字和类存储