std::函数向量

发布于 2024-07-26 16:08:32 字数 383 浏览 3 评论 0原文

我想要一个 std::vector 包含一些函数,并且可以实时向其中添加更多函数。 所有函数都将具有如下原型:

void name(SDL_Event *event);

我知道如何创建函数数组,但是如何创建函数的 std::vector ? 我已经尝试过这个:

std::vector<( *)( SDL_Event *)> functions;

std::vector<( *f)( SDL_Event *)> functions;

std::vector<void> functions;

std::vector<void*> functions;

但它们都不起作用。 请帮忙

I want a std::vector to contain some functions, and that more functions can be added to it in realtime. All the functions will have a prototype like this:

void name(SDL_Event *event);

I know how to make an array of functions, but how do I make a std::vector of functions? I've tried this:

std::vector<( *)( SDL_Event *)> functions;

std::vector<( *f)( SDL_Event *)> functions;

std::vector<void> functions;

std::vector<void*> functions;

But none of them worked. Please help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

望笑 2024-08-02 16:08:32

尝试使用 typedef:

typedef void (*SDLEventFunction)(SDL_Event *);
std::vector<SDLEventFunction> functions;

Try using a typedef:

typedef void (*SDLEventFunction)(SDL_Event *);
std::vector<SDLEventFunction> functions;
倦话 2024-08-02 16:08:32

尝试这个:

std::vector<void ( *)( SDL_Event *)> functions;

Try this:

std::vector<void ( *)( SDL_Event *)> functions;
奈何桥上唱咆哮 2024-08-02 16:08:32

如果你喜欢 boost 那么你可以这样做:

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <vector>

void f1(SDL_Event *event)
{
    // ...
}

void f2(SDL_Event *event)
{
    // ...
}


int main()
{
    std::vector<boost::function<void(SDL_Event*)> > functions;
    functions.push_back(boost::bind(&f1, _1));
    functions.push_back(boost::bind(&f2, _1));

    // invoke like this:
    SDL_Event * event1 = 0; // you should probably use
                            // something better than 0 though..
    functions[0](event1);
    return 0;
}

If you like boost then then you could do it like this:

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <vector>

void f1(SDL_Event *event)
{
    // ...
}

void f2(SDL_Event *event)
{
    // ...
}


int main()
{
    std::vector<boost::function<void(SDL_Event*)> > functions;
    functions.push_back(boost::bind(&f1, _1));
    functions.push_back(boost::bind(&f2, _1));

    // invoke like this:
    SDL_Event * event1 = 0; // you should probably use
                            // something better than 0 though..
    functions[0](event1);
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文