Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::function -> function pointer

Tags:

c++

functor

bind

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.

like image 381
fogbit Avatar asked May 11 '12 16:05

fogbit


People also ask

Is STD function a pointer?

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.

How do you get a function pointer in C++?

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.

How do you use 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 .

What is the use of function pointer in C++?

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.


1 Answers

You can't convert a std::function to a function pointer(you can do the opposite). You should use either function pointers, or std::functions. If you can use std::function instead of pointers, then you should.

This makes your code work:

typedef function<void(void)> fp;
like image 59
mfontanini Avatar answered Sep 30 '22 09:09

mfontanini