函数指针和typedef

昨天在读一个SDK的sample,看到一句特别奇怪的用了typedef(C++ Primer P60)的语句。看了很久,查了资料才知道是做什么的。

	typedef void (*PFuncOnTouchGesture)(const TouchGesture & tg,void * call_object);

问了大神之后,给我发了wikipedia的链接,看了一下属于 Using typedef with function pointers这一种用法,就是给函数指针重新命名的意思吧。

函数指针(C++ Primer P221)的定义也不是很清楚,

函数指针指向的是函数而非对象。函数的类型,是由返回类型和形参类型共同决定的,要想定义一个指向特定类型的函数的函数指针,就用指针替换函数名即可。

看这一句语句,函数指针是 void (*PFuncOnTouchGesture)(const TouchGesture &tg,void *call_object); 就是指向一个返回类型为void,形参类型为const TouchGesture &tg,void *call_object的函数。

下面代码是没有使用typedef来定义函数指针的类型别名的情况:

int do_math(float arg1, int arg2) {
    return arg2;
}

int call_a_func(int (*call_this)(float, int)) {
    int output = call_this(5.5, 7);
    return output;
}

int final_result = call_a_func(&do_math);

This code can be rewritten with a typedef as follows:

typedef int (*MathFunc)(float, int);

int do_math(float arg1, int arg2) {
    return arg2;
}

int call_a_func(MathFunc call_this) {
    int output = call_this(5.5, 7);
    return output;
}

int final_result = call_a_func(&do_math);

Here, MathFunc is the new alias for the type. A MathFunc is a pointer to a function that returns an integer and takes as arguments a float followed by an integer.

When a function returns a function pointer, it can be even more confusing without typedef. The following is the function prototype of signal(3) from FreeBSD:

void (*signal(int sig, void (*func)(int)))(int);

The function declaration above is cryptic as it does not clearly show what the function accepts as arguments, or the type that it returns. A novice programmer may even assume that the function accepts a single int as its argument and returns nothing, but in reality it also needs a function pointer and returns another function pointer. It can be written more cleanly:

typedef void (*sighandler_t)(int);
sighandler_t signal(int sig, sighandler_t func);

再回到这里

typedef void (*PFuncOnTouchGesture)(const TouchGesture & tg,void * call_object);
PFuncOntouchGesture就是一个 指向某种特定类型的函数的指针的别名,实际就是一种类型的别名。这种类型代表了一类的指向函数的指针。有点绕来绕去了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值