"store" function to a variable and call it using that variable?

I want to store few different functions to a variable for different structs/classes and then call it later using that variable, is it possible? something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct item
{
	int ID;
	int special; // for function
};

item Key;
Key.special = UseKey(KEY_KING);

// now when I want to call function "UseKey(KEY_KING)" I want to use "Key.special", like this

if(iCurrRoom == ROOM_KING)
	Key.special;
else if(iCurrRoom == ROOM_DRAGON)
	Fireball.special;
Look up function pointers and std::function
It sounds like you want "special" to be a pointer to a function. Instead of making it an integer, make it an std::function (or pointer to a function) with the same signature as the kind of functions you'll assign to it.

1
2
3
4
5
6
7
8
9
10
11
struct item
{
    int ID;
    std::function<void()> special; // special will reference a void-returning function with no parameters
};

item Key;
Key.special = std::bind(&UseKey, KEY_KING); // set special to call UseKey with the parameter KEY_KING

// then you can use it like so:
(Key.special)(); // full parens may not be necessary 
so, since i want to pass (and you are also passing) parameter KEY_KING when binding function on line 8, should I in struct declare the variable as

std::function<void(int)> special

since I want it to take 1 int argument?
No, by binding the argument it is passed for you so you don't need to indicate that that argument even exists anymore.
thanks !: )
Topic archived. No new replies allowed.