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.
Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.
A function is defined as a relation between a set of inputs having one output each. In simple words, a function is a relationship between inputs where each input is related to exactly one output. Every function has a domain and codomain or range.
Use the keyword def to declare the function and follow this up with the function name. Add parameters to the function: they should be within the parentheses of the function. End your line with a colon. Add statements that the functions should execute.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With