I have a function void f (void*, int);
, that is used as a callback function. The caller expects void (*)(int)
. Can I use std::bind1st
to convert one to another? Is there any way to do this without using C++ 11 std::bind
, just std::bind1st
?
Asked
Active
Viewed 121 times
0

Violet Giraffe
- 32,368
- 48
- 194
- 335
1 Answers
2
No. Although std::bind1st()
creates a function object with a call operator taking and int
, it is not a void(*)(int)
. The only way to turn a void(*)(void*, int)
into a void(*)(int)
is to have a forwarding function which obtains the void*
from global resources, e.g.,
static void* data = 0; // probably needs to be set to a more suitable value
void f_forward(int value) {
f(data, value);
}
Anybody providing a callback which doesn't take a user-defined context, e.g., in the C-like interface a void*
which is just passed through, didn't think too hard about the interface.

Dietmar Kühl
- 150,225
- 13
- 225
- 380
-
Indeed. I was hoping to avoid a global / static variable. Thanks for the answer. – Violet Giraffe Dec 16 '13 at 10:01
-
@violetgiraffe The other way is to write self modifying code, which is both non portable and lower level than C++. Basically get a writable page from the OS, blit a known function with a constant embedded in the machine code, modify that constant, mark the page as read only and executable, then take a pointer to the function with the 'hard-coded' `void*`. And yes, this is doable on many platforms, it is just rarely wise. Use a global, and if you need more than one, use a set of `N` and a global array, and assert that you use no more than `N`. – Yakk - Adam Nevraumont Dec 16 '13 at 10:15