Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is storing any type of function in one variable possible?

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.

like image 683
Rhyme Avatar asked Mar 19 '19 09:03

Rhyme


People also ask

Can you store a function in a variable?

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.

How do you define a function?

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.

How do you make a function a parameter in Python?

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.


1 Answers

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.

like image 181
Petar Velev Avatar answered Sep 28 '22 00:09

Petar Velev