问题描述
like:vector<void *(*func)(void *)>
...
like: vector<void *(*func)(void *)>
...
推荐答案
您可以声明一个指向函数的指针向量,该函数采用单个void *
参数并返回void *
,如下所示:
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;
}
您可以使用typedef
来部分隐藏函数强制转换语法,但是仍然存在将函数调用为错误类型的危险,从而导致崩溃或其他未定义的行为.所以不要这样做.
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.
这篇关于如何在向量中存储函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!