drop-in replacment for function pointers

O

Oliver Kowalke

Hello,
I've to use a function from c-library (third party) which expects a
function pointer (void(*FunctionPointer)(int)). Instead of using a
global function (with the signature of the function pointer) I'de like
to use a functor (in order to provide a statefull function). Is this
possible? If yes how?
thx,
Oliver
 
V

Victor Bazarov

Oliver Kowalke said:
I've to use a function from c-library (third party) which expects a
function pointer (void(*FunctionPointer)(int)). Instead of using a
global function (with the signature of the function pointer) I'de like
to use a functor (in order to provide a statefull function). Is this
possible? If yes how?

It's possible if you define a class with static data members (your
state is kept there) and a static function member, a pointer to which
you're going to give to the c-library. It's not the same as functor,
of course. Essentially it is very much like keeping your state in
a set of global variables. It's a bit better, still.

The biggest difference between functors who keep their state in their
non-static data members and a class with static data is that you can
have "unlimited" number of functors running around and only one class
"instance". You can overcome this by having multiple instances of the
class (using templates), but it's a bit trickier than functors which
you can instantiate as needed.

V
 
J

Jesper Madsen

Victor Bazarov said:
It's possible if you define a class with static data members (your
state is kept there) and a static function member, a pointer to which
you're going to give to the c-library. It's not the same as functor,
of course. Essentially it is very much like keeping your state in
a set of global variables. It's a bit better, still.

The biggest difference between functors who keep their state in their
non-static data members and a class with static data is that you can
have "unlimited" number of functors running around and only one class
"instance". You can overcome this by having multiple instances of the
class (using templates), but it's a bit trickier than functors which
you can instantiate as needed.

V

Should it not be possible to use boost::bind to create a function with a
void (*func)(int) signature..?
 
V

Victor Bazarov

Jesper Madsen said:
[..]
Should it not be possible to use boost::bind to create a function with a
void (*func)(int) signature..?

Could as well be. I don't know Boost. It's not part of Standard C++.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top