Sign in to follow this  
Decrius

C++ function pointers

Recommended Posts

I'm making a GUI library and I want to bind specific functions to certain actions. Actions may be: mouse click, keyboard hit etc The component class would hold a pointer to the function specified by the user. However, this function should not be bound to certain parameters. It would be best if the user can define the number and type of parameters, this can be anything so I'm not quite sure IF this is possible and how I would implement it...for example, how do I define the pointer in the class? Is this possible? Can I have a pointer to a function with variable parameters? How would I store the parameters (they would be set at pointer initialisation)? How can I make this as userfriedly and useable as possible? Or should I just use void *data as parameter, and let the user use a struct for example? Thanks.
void mouse_in(int x, int y, char *data)
{
    std::cerr << "executing function";
}

namespace GUI
{
    Button::set_event(Event type, void *function_ptr, ...)
    {
        // do something like
        if (type == Event::MouseIn)
        {
            function_ptr(x, y, /* data via the va_ lib should be put here */);
        }
    }

int main(int argc, char *argv[])
{
    GUI::Button button;

    button.set_event(OpenGUI::Event::MouseIn, mouse_in, "this is the data that should be passed (char *data)");

    return 0;
}
Would this syntax be possible for instance? Or what would you suggest? Thanks alot, Decrius

Share this post


Link to post
Share on other sites
There is always the dreaded ... construct like what printf uses. Though I would consider that to be a bit over the top. Though I am curious how you expect them to be able to set parameters when the event hits? How do I hook in to the left mouse click to set arbitrary parameters? The events should bubble up from the system the event handler should be the first place they can hook into it.

A second idea, provide a MouseEvent class that they can derive from. They can then down cast it in the call back.

Share this post


Link to post
Share on other sites
boost::bind and boost::function for the win. It's rediculously simple to use compared with the other methods presented.

It's not as fast as FastDelegates, but that code makes me a little nevrvous - probably unjustifiably so, as I have never actually used FastDelegates..

I stick with boost because it's a well established library and you get alot more stuff along with bind, e.g. Boost.Python, format, regex etc. which are all really handy and time saving (once you get comfortable with it)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this