jeudi 22 novembre 2018

Make a virtual function that returns a generic member function pointer

I want to write an abstract class named COMMUNICATOR that has a virtual function get_func().

class COMMUNICATOR{
public:
    virtual <what type???> get_func() = 0;
};

Now suppose INT_SENDER, INT_RECEIVER, STR_SENDER, and STR_RECEIVER all derive from COMMUNICATOR. They each provide their own implementation of get_func(), and they can be used like this:

COMMUNICATOR *int_sender = new INT_SENDER;
COMMUNICATOR *int_receiver = new INT_RECEIVER;

COMMUNICATOR *str_sender = new STR_SENDER;
COMMUNICATOR *str_receiver = new STR_RECEIVER;

//INT_SENDER::get_func() and INT_RECEIVER::get_func() both return a member functions pointer of signature void(*)(int)
connect( int_sender, int_sender->get_func(), int_receiver, int_receiver->get_func() );

//STR_SENDER::get_func() and STR_RECEIVER::get_func() both return functions of signature void(*)(std::string)
connect( str_sender, str_sender->get_func(), str_receiver, str_receiver->get_func() );

What I want to achieve with this design are:

(1) To give all classes that derive from COMMUNICATOR the same interface: the get_func() function

(2) Using COMMUNICATOR and its derived classes does not require dealing with the signature of the function returned by get_func(). Instead, the function pointers are passed directly into connect();

Is there some sort of hack to achieve what I want, like making get_func() return some type-erasing wrapper object from which I can dump a function pointer into connect()? Or am I attempting the impossible here?

Aucun commentaire:

Enregistrer un commentaire