Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing std::tr1::function<> objects

Tags:

c++

function

tr1

I've been trying to implement a C#-like event system in C++ with the tr1 function templates used to store a function that handles the event.

I created a vector so that multiple listeners can be attached to this event, i.e.:

vector< function<void (int)> >  listenerList;

I'd like to be able to remove a handler from the list to stop a listener receiving events.

So, how can I find the entry in this list that corresponds to a given listener? Can I test if a 'function' object in the list refers to a particular function?

Thanks!

EDIT: Having looked into the boost::signal approach, it seems it's probably implemented using a token system as some of you have suggested. Here's some info on this. An observer retains a "Connection" object when they attach to an event, and this connection object is used to disconnect if needed. So it looks like whether you use Boost or roll your own with tr1, the basic principle's the same. i.e. it will be a bit clumsy :)

like image 445
AlexG Avatar asked Sep 18 '08 02:09

AlexG


3 Answers

I don't know if you're locked into std C++ and tr1, but if you aren't, it seems like your problem could be completely avoided if you just used something like boost::signal and boost::bind to solve your original problem - creating an event system - instead of trying to roll your own.

like image 165
Nick Bastin Avatar answered Nov 01 '22 05:11

Nick Bastin


FAQ #1 in the boost function documentation seems to address your question - and the easy answer is "no".

like image 42
Matt Cruikshank Avatar answered Nov 01 '22 05:11

Matt Cruikshank


The proposal (section IIIb.) states they will not be comparable in any way. If you attach some extra information to them, you can easily identify each callback. For instance, if you simply define a struct wrapping the function pointer, you can remove them (assuming you have the same struct you inserted). You can also add some fields to the struct (like an automatically generated guid the client can hold on to) and compare against that.

like image 1
hazzen Avatar answered Nov 01 '22 04:11

hazzen