1class Foo {
2 int (*func)(int);
3
4public:
5 void setCallback( int (*cFunc)(int) ) {
6 func = cFunc;
7 }
8
9 void set() {
10 setCallback(callback); // Set callback function to be called later
11 }
12
13 void use() {
14 func(5); // Call the previously set callback function
15 }
16
17 // Note the 'static'
18 static int callback(int param) {
19 return 1;
20 }
21};
1//Define a type for the callback signature,
2//it is not necessary, but makes life easier
3
4//Function pointer called CallbackType that takes a float
5//and returns an int
6typedef int (*CallbackType)(float);
7
8
9void DoWork(CallbackType callback)
10{
11 float variable = 0.0f;
12
13 //Do calculations
14
15 //Call the callback with the variable, and retrieve the
16 //result
17 int result = callback(variable);
18
19 //Do something with the result
20}
21
22int SomeCallback(float variable)
23{
24 int result;
25
26 //Interpret variable
27
28 return result;
29}
30
31int main(int argc, char ** argv)
32{
33 //Pass in SomeCallback to the DoWork
34 DoWork(&SomeCallback);
35}
36
1// C++ callback function
2
3class Base {
4public:
5 void doSomething() {
6 using namespace std::placeholders;
7 // std::placeholders::_1 is for the callback parameter
8 // use _1 for 1 argument
9 // or _1, _2, _3 for 3 arguments and so on
10 something.setCallback(std::bind(&Base::callback, this, _1));
11 // std::bind is needed, otherwise
12 // the callback function would need to be static
13 }
14
15 // Callback function
16 void callback(int i) {
17 std::cout << "Callback: " << i << std::endl;
18 }
19}