11

I'm trying to make a menu array where each element is a struct that stores variables for text, key that needs to be pressed to select that item and function called on that key press (something like "Quit", 'Q', Quit()). I thought this would make things more efficient, but I can't find a way to make it work with varied function and parameter types (for example one item should be able to call a void function with no parameters, another a class int function with two parameters and so on). Is there a good way to do this or am I better off giving up on the idea?

Edit: Thank you all for your advice! The proposed solutions feel a little too complex for my newbie self, but attempting to understand them gave me some ideas! I ended up making the third variable hold an enum instead of a direct function call and then created a switch function that calls other functions based on that value.

Rhyme
  • 121
  • 7

2 Answers2

10

There are actually a few ways of doing this.

One way is to use std::bind to bind all functions to void func(void) then you can store them equally.
The other way is to create a generic function/lambda which will call your function.
To store your functions you can use std::function.

Also consider overriding operator() of your classes.

Petar Velev
  • 2,305
  • 12
  • 24
1

The classic way of handling this is to have all the functions take the same parameters, and for those to be very flexible. For example, an integer or enum, and a pointer.

  • your no-parameter function is passed -1 and nullptr and ignores them
  • your multi-parameter function casts the pointer to a pointer to some struct or class that holds all the bits and pieces it needs (and of course your calling code made that instance and passed its address)

The reason an enum or integer is hoisted out as one of the parameters is that "command type" is a super popular thing to need, so why do all that casting and extracting to get it?

If you have a performance problem as a result of this approach, then there are others, but this has literally been used for decades in Windows.

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85