开发者

How can I store function pointer in vector?

开发者 https://www.devze.com 2023-01-17 11:09 出处:网络
like:vector<void *(*func)(voi开发者_Go百科d *)>...You can declare a vector of pointers to functions taking a single void * argument and returning void * like this:

like: vector<void *(*func)(voi开发者_Go百科d *)>...


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 4.

    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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消