by Max Z.C. Li maximusl@g.ucla.edu
open notes, all corrections and additions welcomed, many thx!
- by pointer
- by type
- by < functional >
functions cannot have instances, so their names are already pointers; therefore the methods are only stylishly different.
see code below:
#include <iostream>
#include <functional>
using namespace std;
typedef int (*fptr) (int, int); //fptr is a pointer to int funName(int, int) type functions
//you can also do return_type (*funName) (params) as type for the pass-by-pointer to the functions
typedef int (ftype1) (int, int); //ftype 1 is the above type
typedef function<void(int)> ftype2; //using functional library, ftype2 is a void funName(int) type function
void foo(int a){
cout << "foo: " << a << endl;
}
int add(int a, int b){
return a+b;
}
void printAdd(int a, int b, int op(int, int), void prt(int) ){
prt(op(a,b));
}
void printAdd2(int a, int b, fptr op, void (*prt)(int) ){// foo* is void (*)(int), cannot be converted to function<void(int)>* ==? ftype2* does not work
(*prt)((*op)(a,b)); //function pointer must be de-ref-ed first
//specify order of operations with ()
}
void printAdd3(int a, int b, ftype1 op, ftype2 prt){
prt(op(a,b));
}
int main(){
printAdd(1,2, add, foo);
printAdd(2,3, &add, &foo);
printAdd2(1,2, add, foo);//function names are pointers naturally
printAdd2(2,3, &add, &foo);
printAdd2(1,2, add, foo);
printAdd2(2,3, &add, &foo);
}
an additional note about “callback functions” from here
使用回调函数实际上就是在调用某个函数(通常是API函数)时,将自己的一个函数(这个函数为回调函数)的地址作为参数传递给那个函数
//so that communications of the two blocks can be managed smoothly ==> check the result in the caller’s own stack.