std::vector of functions

2020-07-03 04:30发布

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

3条回答
Melony?
2楼-- · 2020-07-03 05:15

Try using a typedef:

typedef void (*SDLEventFunction)(SDL_Event *);
std::vector<SDLEventFunction> functions;
查看更多
迷人小祖宗
3楼-- · 2020-07-03 05:19

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;
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-07-03 05:35

Try this:

std::vector<void ( *)( SDL_Event *)> functions;
查看更多
登录 后发表回答