如何在向量中存储函数指针? [英] How can I store function pointer in vector?

查看:73
本文介绍了如何在向量中存储函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于如何在向量中存储函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆