Here is a code:
#include <functional>
using namespace std::tr1;
typedef void(*fp)(void);
void foo(void)
{
}
void f(fp)
{
}
int main()
{
function<void(void)> fun = foo;
f(fun); // error
f(foo); // ok
}
Originally i need to make a function pointer from non-static class method because i need to save data between function callings. I tried std::tr1::bind
and boost::bind
, but they return functional object, not pointer, which, as i can see, can't be "casted" to pure functional pointer. While the function signature (SetupIterateCabinet
) demands a pure func pointer exactly.
I need an advise how to solve the problem. Thank you.
No. One is a function pointer; the other is an object that serves as a wrapper around a function pointer. They pretty much represent the same thing, but std::function is far more powerful, allowing you to do make bindings and whatnot.
Function Pointer Syntaxvoid (*foo)( int ); In this example, foo is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*foo", which takes an int and returns void; now, if *foo is a function, then foo must be a pointer to a function.
You can use a trailing return type in the declaration or definition of a pointer to a function. For example: auto(*fp)()->int; In this example, fp is a pointer to a function that returns int .
It is basically used to store the address of a function. We can call the function by using the function pointer, or we can also pass the pointer to another function as a parameter. They are mainly useful for event-driven applications, callbacks, and even for storing the functions in arrays.
You can't convert a std::function
to a function pointer(you can do the opposite). You should use either function pointers, or std::function
s. If you can use std::function
instead of pointers, then you should.
This makes your code work:
typedef function<void(void)> fp;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With