How can I store function pointer in vector?

2019-05-22 14:45发布

问题:

like: vector<void *(*func)(void *)>...

回答1:

You can declare a vector of pointers to functions taking a single void * argument and returning void * like this:

#include <vector>
std::vector<void *(*)(void *)> v;

If you want to store pointers to functions with varying prototypes, it becomes more difficult/dangerous. Then you must cast the functions to the right type when adding them to the vector and cast them back to the original prototype when calling. Just an example how ugly this gets:

#include <vector>

int mult(int a) { return 2*a; }

int main()
{
    int b;

    std::vector<void *(*)(void *)> v;
    v.push_back((void *(*)(void *))mult);
    b = ((int (*)(int)) v[0])(2);        // The value of b is 2.

    return 0;
}

You can use typedef's to partially hide the function casting syntax, but there is still the danger of calling a function as the wrong type, leading to crashes or other undefined behaviour. So don't do this.



回答2:

Storing a function in vector might be a difficult task as illustrated above. In that case if u want to dynamically use a function u can also store a function in pointer which is much easier. Main advantage of this is u can store any type of function either it is a normal function or a paramatrized one(having some input as parametrs). Complete process is described in the link given below with examples...just have a look...!!! how can we store Function in pointer