I'm trying to use std::function
in conjunction with std::bind
, but I'm having some problems.
This works:
#include <functional>
#include <iostream>
void print() {
std::cout << 2;
}
int main() {
std::function<void ()> foo = print;
(*foo.target<void (*)()>())(); //prints 3
}
This crashes at the second line of main
:
#include <functional>
#include <iostream>
void print (int i) {
std::cout << i;
}
int main() {
std::function<void ()> foo = std::bind (print, 2);
(*foo.target<void (*)()>())();
}
I'm really holding the std::function<void ()>
and need to be able to return the function; not just call it. I expect the usage would be something like this:
#include <functional>
#include <iostream>
void print (int i) {
std::cout << i;
}
int main() {
Container c (std::bind (print, 2));
//I would expect the original
c.func() (3); //prints 3
if (c.func() == print) /* this is what I'm mostly getting at */
}
Is there any way to get the original function to return it, or an alternative? It does kind of conflict with the return type as well, as void (*)()
matches the bound signature quite nicely.
You can't get a function pointer out of an
std::function
, as there may not even be one. It could be a member function pointer instead, or an object that implementsoperator()
.This can be achieved using a little template meta-programming. I recently had use for this while writing a generic C++ wrapper around OpenGL GLUT (which depends on callback function pointers). The approach:
Tested under C++11 on GCC 4.8.
This is quite impossible. The whole reason that
std::function
exists is that function pointers suck horrifically and should never, ever, be used by anyone, ever again, except for the doomed souls bearingthe Burning Standards of HellC interoperation, because they cannot handle functions with state.A
std::function<void()>
cannot, in the general case, be converted to avoid(*)()
. The only reason this works in the first example is because it happens to be avoid(*)()
originally.