C++- various callback functions and related arguments to write
"This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021"
The callback function
Pass a pointer to a function and call the function to which the pointer points. The called function is called a callback. Once you've learned the concept of callable objects, you can pass in a variety of callable objects to implement callbacks.
Go straight to code
class TestClass
{
public:
int add(int a, int b) { return a + b; }//public member function
};
class TestClass2
{
public:
static int add(int a, int b) { return a + b; }// Static member functions
};
class TestClass3
{
public:
int operator(a)(int a, int b) { return a + b; }// Overrides the class that calls the operator
};
int callFunc(int a, int b, int (*p)(int.int)) {// Pass in the function pointer
return p(a, b);
}
int callFunc2(int a, int b, functionint(int.int) func) {// Pass in the function type function
return func(a, b);
}
int callFunc3(int a, int b, int (TestClass::*p)(int.int)) {// Pass in a method for a specific class
TestClass obj;
return (obj.*p)(a, b);
}
int callFunc4(int a, int b, TestClass3 callableObj) {// Pass in the callable
return callableObj(a, b);
}
int add(int a, int b) {// A normal function
return a + b;
}
cout callFunc(2.3, add) endl;// If you pass in a function, it is automatically converted to a pointer to the function
cout callFunc(2.3[] (int a, int b) {return a + b; }) endl;// Pass in a lambda expression
cout callFunc(2.3, TestClass2::add) endl;// Pass in static member member functions
cout callFunc2(4.5.bind(add, _1, _2))endl;Function
cout callFunc3(6.7, TestClass::add) endl;// Pass in the class member function
TestClass obj;
cout callFunc2(8.9.bind(TestClass::add,obj,_1,_2))endl;Function
TestClass3 obj3;
cout callFunc4(10.11, obj3)endl;// Pass in the callable
cout callFunc2(12.13.bind(TestClass3::operator(),obj3,_1,_2))endl;Function
Copy the code
From the above code, we can see that the function interface in the form of callFunc2 has good universality, and the reason why we use the callback function is to want more "universality", let the interface caller decide what function is passed in.
CallFunc2 can be passed into any callable for a callback, with function
Note: Embarrassing is that the above example I wrote in the middle of the security software prompted me to write exe is a virus, estimated and some characteristics of the callback function, directly false positive.