What is the Callbak feature?
In simple words, the Callback function is a function that is not explicitly called by the programmer. Instead, there is some mechanism that is constantly waiting for events, and it will call the selected functions in response to certain events.
This mechanism is usually used when an operation (function) can take a long time to execute, and the calling function object does not want to wait for the operation to complete, but wants to be informed about the results of the operation. As a rule, callback functions help to implement such an asynchronous mechanism., , , , .
:
Windows:
Windows , (, , , ) . , , , () , , . .
:
#include <map>
typedef void (*Callback)();
std::map<int, Callback> callback_map;
void RegisterCallback(int event, Callback function)
{
callback_map[event] = function;
}
bool finished = false;
int GetNextEvent()
{
static int i = 0;
++i;
if (i == 5) finished = false;
}
void EventProcessor()
{
int event;
while (!finished)
{
event = GetNextEvent();
std::map<int, Callback>::const_iterator it = callback_map.find(event);
if (it != callback_map.end())
{
Callback function = *it;
if (function)
{
(*function)();
}
else
{
std::cout << "No callback found\n";
}
}
}
}
void Cat()
{
std::cout << "Cat\n";
}
void Dog()
{
std::cout << "Dog\n";
}
void Bird()
{
std::cout << "Bird\n";
}
int main()
{
RegisterCallBack(1, Cat);
RegisterCallback(2, Dog);
RegisterCallback(3, Cat);
RegisterCallback(4, Bird);
RegisterCallback(5, Cat);
EventProcessor();
return 0;
}
:
Cat
Dog
Cat
Bird
Cat
, !
: ,