In c++, when and how to use a callback function?
EDIT: I would like to see a simple example to write a callback function.
In c++, when and how to use a callback function?
EDIT: I would like to see a simple example to write a callback function.
A Callback function is a method that is passed into a routine, and called at some point by the routine to which it is passed.
This is very useful for making reusable software. For example, many operating system APIs (such as the Windows API) use callbacks heavily.
For example, if you wanted to work with files in a folder - you can call an API function, with your own routine, and your routine gets run once per file in the specified folder. This allows the API to be very flexible.
homework?
There isn't an explicit concept of a callback function in C++. Callback mechanisms are often implemented via function pointers, functor objects, or callback objects. The programmers have to explicitly design and implement callback functionality.
Scott Meyers gives a nice example:
class GameCharacter;
int defaultHealthCalc(const GameCharacter& gc);
class GameCharacter
{
public:
typedef std::tr1::function<int (const GameCharacter&)> HealthCalcFunc;
explicit GameCharacter(HealtCalcFunc hcf = defaultHealtCalc)
: healtFunc(hcf)
{ }
int healtValue() const { return healthFunc(*this); }
private:
HealthCalcFunc healtFunc;
};
I think the example says it all.
tr1::function<>
is the "modern" way of C++ callbacks.
You also could consider using an event-type system in lieu of callbacks.
http://cratonica.wordpress.com/2010/02/19/implementing-c-net-events-in-c/
There is also the C way of doing callbacks: function pointers
//Define a a type for the callback signature,
//it is not necessary, but makes life easier
//Function pointer called CallbackType that takes a float
//and returns an int
typedef int (*CallbackType)(float);
void DoWork(CallbackType callback)
{
float variable = 0.0f;
//Do calculations
//Call the callback with the variable, and retrieve the
//result
int result = callback(variable);
//Do something with the result
}
int SomeCallback(float variable)
{
int result;
//Interpret variable
return result;
}
int main(int argc, char ** argv)
{
//Pass in SomeCallback to the DoWork
DoWork(&SomeCallback);
}
Now if you want to pass in class methods as callbacks, the declarations to those function pointers have more complex declarations, example:
//Declaration:
typedef int (ClassName::*CallbackType)(float);
void DoWork(CallbackType callback)
{
//Class instance to invoke it through
ClassName instance;
//Invocation
int result = instance->*callback(1.0f);
}
int main(int argc, char ** argv)
{
//Pass in SomeCallback to the DoWork
DoWork(&ClassName::Method);
}