Another keyboard event question in C++

Hi all (again),

I’ve been busy translating the Roaming Ralph tutorial to C++. It’s almost done – Just the animation part.
But, I’m having some trouble with the keypresses too. Usually, it works fine:

void exit_event(const Event * theEvent, void * data) {
  exit(0);
}
//...
World::World(WindowFramework *window) {
  //...
  framework_ptr=window->get_panda_framework();
  //...
  framework_ptr->define_key("escape", "Quit", exit_event, 0);
  //...
}

Though, once I want an event to a function within my class World, It won’t work anymore:

World::World(WindowFramework *window) {
  //...
  pair<string, bool> data=("left", true);
  framework_ptr->define_key("arrow_left", "Rotate Ralph Left", set_key, (void *) &data);
  //...
}
World::set_key(const Event * theEvent, void * data) {
  //...
}

That throws an error because there is no overloaded function for define_key. If I make set_key a global function instead of a subfunction of the class World it works.

Does anybody have an idea how to correct this? Thanks in advance.

The problem is the hidden “this” pointer to set_key(), which makes it no longer match the function prototype expected by define_key(). To avoid this, you have to declare set_key() to be a static method. (You can use the data pointer to pass in the this pointer again.)

David

Oh, right, sorry, forgot about that. I’ll try out your suggestion.

OK, so this is very annoying. Since I can’t access non-static members from within a static function, I have to define all variables I want to use from within that function globally.
Isn’t there a way to tell define_key that it takes another argument, the this pointer? Or perhaps a better way to do things?

I usually write a static function that extracts the this parameter from its data parameter, and then uses that this pointer to call a non-static version of itself.

David

Excellent solution! Thanks a lot.