mercredi 14 novembre 2018

C++ template class with dynamic callback function type

In the code below, I want a user to be able to create a consumer class with a specific type, eg Consumer<StateA> so their callback function can correctly handle the type they give it. However in the code below, the compiler complains because at compile time, the call to the function in the StateB consume method is not generated. The consume methods come from a base class and they have to be overriden.

template <class T>
class Consumer : ConsumerBase
{
    public:
        Consumer(std::function<void(T&)> _callback){
            callback = _callback;
        }
        virtual void consume(StateA& state) { 
            callback(state);
        }
        virtual void consume(StateB& state) { 
            callback(state);
        }
    private:
        std::function<void(T&)> callback; 
};

How can I make this work?

Aucun commentaire:

Enregistrer un commentaire