Assign Function Reference

Is it possible to store a pointer to a function inside a variable? I feel like it is but I just can't figure out how to do it. I specifically want to try to create an array of pointers to functions, so users can input a number corresponding to a specific function, and that number would be the index of a pointer to a function inside an array.

e.g.
1
2
3
4
5
6
7
int add(int a, int b){return (a+b);} //basic adding function

int (*addP)(int,int); //pointer to basic adding function

int funcArray[] = {addP}; //array with my one function reference

funcArray[0](6,4); //forgot to dereference, but I have no clue how'd that work 


If this is possible, an example would be greatly appreciated. If not, but you can think of a different route of doing what I wanted to do (stated above), then please tell me. Thanks!
For this, a typedef is helpful:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int func1(int a, int b) {return a + b;}

int func2(int a, int b){return a * b;}

int func3(int a, int b){return a / b;}

//define pFunc as a pointer to a function that returns an int
//and takes two ints
typedef int (*pFunc)(int, int);

//array of pFunc
pFunc arrOfPFunc[3] = {&func1, &func2, &func3};

int result = (*arrOfPFunc[0])(1, 2); //call func1
result = (*arrOfPFunc[1])(2, 3); //call func2
result = (*arrOfPFunc[2])(3, 4); //call func3 
Thank-you so much! This is exactly what I needed. This just saved me the time of creating a looong conditional! :D
Keep in mind that pointers and references are different (in particular, array cannot hold a reference, unless it's wrapped)

If you really want arrays, your choices are:
array of pointers to functions
array of reference_wrappers, holding references to functions
array of std::function objects
But you don't have to resort to arrays, you could just use vectors, or pick another suitable container. For a typical task of choosing which operation to execute based on some key, a map<key, std::function> works best.

Here's the three arrays for completeness

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <functional>
int add(int a, int b){return a+b;}
int sub(int a, int b){return a-b;}
int mul(int a, int b){return a*b;}

int main()
{
    // array of pointers to functions
    int (*arr1[])(int, int) = {add, sub, mul};
    // array of std::reference_wrappers
    std::reference_wrapper<int(int, int)> arr2[] = {std::ref(add), std::ref(sub), std::ref(mul)};
    // array of std::functions
    std::function<int(int,int)> arr3[] = {add, sub, mul};

    // let's use them
    std::cout << arr1[0](1, 2) << ' ' << arr1[1](1,2) << ' ' << arr1[2](1,2) << '\n'
              << arr2[0](1, 2) << ' ' << arr2[1](1,2) << ' ' << arr2[2](1,2) << '\n'
              << arr3[0](1, 2) << ' ' << arr3[1](1,2) << ' ' << arr3[2](1,2) << '\n';
}


online demo: http://ideone.com/sVoHc
Last edited on
Topic archived. No new replies allowed.