CPP: 3 ways to pass a function as a parameter CPP 3种传函数作参数写法

51 篇文章 2 订阅

by Max Z.C. Li maximusl@g.ucla.edu
open notes, all corrections and additions welcomed, many thx!

  1. by pointer
  2. by type
  3. 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值