Re: std::map of pointers to member functions

Discussion in 'C++' started by David White, Jul 24, 2003.

  1. David White

    David White Guest

    Jonathan Mcdougall <> wrote in message
    news:...
    > To make a long story short, I need to associate events with pointers
    > to functions. The first idea which came to my mind was
    >
    > enum Event
    > {
    > clicked,
    > moved
    > };
    >
    > typedef void (*Handler)(int);
    >
    >
    > void my_handler(int)
    > {
    > std::cout << "in my handler";
    > }
    >
    >
    > int main()
    > {
    > std::map<Event, Handler> handlers;
    >
    > handlers.insert(std::make_pair(clicked, &my_handler));
    >
    > if ( event_triggered(clicked) )
    > (handlers[clicked])( /*whatever*/ );
    > }
    >
    >
    > I hope this makes sense.
    >
    > Now, the thing is, I need to include member functions too, so I came
    > up with that :
    >
    > template<class Object, class Function> class Handler
    > {
    > private:
    > Object obj_;
    > Function fun_;
    >
    > public:
    > template<class Object, class Function>
    > Handler(Object obj, Function fun)
    > : obj_(obj),
    > fun_(fun)
    > {
    > }
    >
    > void operator()(int whatever)
    > {
    > ((*obj_).*fun_)(whatever);
    > }
    > };
    >
    > But now I am stuck with the std::map, since it cannot accept templates
    > (as I understand).


    What the map cannot accept is its values being of different types. It just
    happens that your template is the thing that produces the different types in
    this case. I think you need an ordinary Handler class, objects of which are
    what you give to the map, and worry about how you store the different class
    and member function within the Handler class. Possible ways are virtual
    functions (where each overriding class has the right object of the right
    class and the right member function pointer), or a pointer to an
    intermediate static or global function in which you can keep well-hidden a
    nasty cast of the void pointer passed to it to an object pointer and a call
    to the appropriate member function.

    DW
     
    David White, Jul 24, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Victor Bazarov
    Replies:
    1
    Views:
    449
    Jonathan Mcdougall
    Jul 25, 2003
  2. Peter Jansson
    Replies:
    5
    Views:
    6,399
    Ivan Vecerina
    Mar 17, 2005
  3. Replies:
    1
    Views:
    444
    red floyd
    Dec 21, 2008
  4. Thomas J. Gritzan
    Replies:
    6
    Views:
    1,040
    James Kanze
    Dec 22, 2008
  5. James Kanze
    Replies:
    0
    Views:
    2,051
    James Kanze
    Dec 21, 2008
Loading...

Share This Page