Pass C function as argument to a function
int myfun(int(*funpt)(int, int)){
int sum = 0;
for(int i = 0; i < 3; i++){
sum += (*funpt)(i, i);
}
return sum;
}
int add(int a, int b){
return a + b;
}
int num = myfun(add);
// how to pass paramter from outside to add
// int a=1, b=2; add(a, b)
funpt is function pointer, (*funpt) is a function which have two parameters: int, int and return type is int. myfun only accept function pointer has the same signature, otherwise there is compiling error.
Pass function to a function pointer
In order to assign a function to other function pointer. *funpt and add both have to have the same signature.
int(*funpt)(int, int);
int addMe(int a, int b){
return a + b;
}
funpt = &addMe;
printf("num=%d\n", (*funpt)(1, 2));
printf("funpt=x%x\n", funpt);
printf("&add=x%x\n", &addMe);
C++ unique_ptr, C++ Smart pointer
template<typename T1, typename T2>
class MyTuple{
public:
T1 x;
T2 y;
public:
MyTuple<T1, T2>(){
}
MyTuple<T1, T2>(T1 t1, T2 t2){
x = t1;
y = t2;
}
};
unique_ptr<MyTuple<int, int>> tuplept(new MyTuple<int, int>(1, 2));
cout<<"x="<<tuplept -> x<<endl;
cout<<"y="<<tuplept -> y<<endl;