Pregunta

I'm currently trying to build a class hierarchy automatically by using C++ templates. The final result is a message handler class that provides handler functions for all possible messages, given in a typelist.

However when inheriting from that class hierarchy and trying to implement the handler function to actually do the application code for some types only, C++ isn't calling the function from the base class.

The following is a minimal and complete example what I'm trying to achieve. It doesn't compile because C++ complains about not finding an overload for 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 );
}
¿Fue útil?

Solución

You need to use handle from you Handle<MsgList> in your MyHandler class

using Handler<MsgList>::handle;

Right now it is hidden and do not overload the name handle in MyHandler class. And taking into account the code of the Handler, you know this :-)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top