Advertisement

Is there something like a pointer to member function?

Started by November 28, 2024 08:33 AM
1 comment, last by WitchLord 5 days, 9 hours ago

'nother question… I have a fairly complex piece of script code that controls multiple duplicate sets of identical GUI elements. It does this by having the entire control mechanism in a class, which I can just instantiate multiple times. In total there are 20 sets of controls, each with a dozen callbacks that are called when a GUI element ("button", “textbox”, etc.) has something to report.

To call the callbacks, I could use delegates, but this means that instead of having the full logic of the class internal to the class, I end up with a few hundred delegates - one for each callback in each class instance. This is an unattractive option, as it spreads the class logic all over the place.

Is there a way I can do this without delegates? I.e. can I somehow engineer a callback mechanism that avoids the delegates entirely?

Code example:

class example {
  void attach_to_gui (string gui_id) {
    @mybutton = button (...find the button based on its gui_id...);
    mybutton.setcallback (this, button_callback);
  }
  void button_callback () {
    ...
  }
  button @mybutton;
}
example ex1, ex2, ...ex20;

One possible answer is that I could pass the class name as a string, and just look it up myself in the class object. However, I would appreciate the added type safety I would get from a ‘proper’ solution.

johannesg said:
mybutton.setcallback (this, button_callback);

This is basically the delegate that you say you don't want. You're anyway sending the object pointer and the actual method to call, which is precisely what goes into the delegate.

There is currently no script syntax to take the address of a class method and pass that to the application. However, the application can take the delegate and instead of storing it as it is, it can take it apart and store the object pointer and actual class method separately.

The example in the documentation shows how that can be done:

https://angelcode.com/angelscript/sdk/docs/manual/doc_callbacks.html#doc_callbacks_delegate

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

Advertisement