Let's say I have to pass a function pointer to a library, and the library will call that function with no parameters. I got the impression hat std::bind allows me to bind a parameter to the function giving me an address that I can pass to the library so that then the function is called by the library with 0 parameters, on my end it is called with the parameters I want.
Somehow I don't think this is true, but I just wanted to check - is this true?
Yes, bind does it the way you want. You would just bind all the parameters to the function, then you can call it with no arguments. If you want different parameters, just rebind them.
You could make the library take std::function objects instead of C function pointers. :P
I can't see another way around this because when you bind the function you have to store the data that is bound somewhere (part of a class or whatever), but a C pointer doesn't let you do that since it just points to some code (basically).
A problem with this approach (and C style callbacks in general), is that the callback functor (in this case foo) must not go out of scope or be destroyed while there is still possibility of it being called.
@Disch yes I know and am aware of that, however there are situations where the library was poorly designed. Still though, it will help people who find this thread via google.
I have yet to see a respectable/usable library that does not offer a userdata pointer for its callbacks. I would be very curious to know what lib you're using that doesn't have that functionality.
Actually my problem wasn't with a library that didn't have a way to give custom user data - I was just trying to see if I could take some arbitrary std::function and get a c-style function pointer from it. I was wanting to do some magic where I used member functions of a class as my callbacks, but the issue is that the way the this pointer gets passed is implementation defined and I didn't want to relay on that. I've settled on forwarding since it works for what I need.