C:我如何使用可变参数的计数功能的单一功能的指针数组? [英] C: How can I use a single function pointer array for functions with variable parameter counts?

查看:154
本文介绍了C:我如何使用可变参数的计数功能的单一功能的指针数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题pretty多少说明了一切。

我不知道如何做到这一点,并没有任何地方走近任何工作。

下面是一些例子功能:

 添加(INT X,int y)对{
  返回X + Y;
}

 平均值(INT X1,Y1 INT,INT X2,Y2 INT){
  回报(X1 + Y1 + X2 + Y2)/ 4;
}

到目前为止,我已经使用的typedef既试过,但我想不出如何使一些指向两种类型之一:

 的typedef INT(* mathfunc2)(INT X,int y)对;
的typedef INT(* mathfunc4)(INT X1,Y1 INT,INT X2,Y2 INT);????? func_table [2] = {加,意味着};


解决方案

您需要选择一个函数指针类型作为通用函数指针使用,使用该类型来定义数组,使用显式类型转换。铸造一个函数指针类型到另一个,然后再回来是保证preserve值。

在换句话说:

 的typedef INT(* generic_fp)(无效);generic_fp func_table [2] = {(generic_fp)添加,(generic_fp)意味着};

然后调用添加,你需要将它转换回正确的类型:

 结果=((mathfunc2)func_table [0])(X,Y);

如果你发现它更可口您可以定义一些宏:

 的#define FUNC_2(F,P1,P2)((mathfunc2)(F))(P1,P2)
的#define FUNC_4(F,P1,P2,P3,P4)((mathfunc4)(f))的(P1,P2,P3,P4)结果= FUNC_2(func_table [0],X,Y);

The question pretty much says it all.

I'm not sure how to do this and haven't come anywhere near anything that works.

Here's some example functions:

add(int x, int y) {
  return x+y;
}

and,

mean(int x1, int y1, int x2, int y2) {
  return (x1 + y1 + x2 + y2) / 4;
}

So far I've tried using typedef with both, but I can't figure how to make something point to one of either type:

typedef int (*mathfunc2)(int x, int y);
typedef int (*mathfunc4)(int x1, int y1, int x2, int y2);

????? func_table[2] = {add, mean};

解决方案

You need to pick a function pointer type to use as a "generic function pointer", use that type to define your array, and use explicit casts. Casting one function pointer type to another and then back again is guaranteed to preserve the value.

In other words:

typedef int (*generic_fp)(void);

generic_fp func_table[2] = { (generic_fp)add, (generic_fp)mean };

Then to call add, you need to cast it back to the right type:

result = ((mathfunc2)func_table[0])(x, y);

You can define some macros if you find it more palatable:

#define FUNC_2(f, p1, p2) ((mathfunc2)(f))(p1, p2)
#define FUNC_4(f, p1, p2, p3, p4) ((mathfunc4)(f))(p1, p2, p3, p4)

result = FUNC_2(func_table[0], x, y);

这篇关于C:我如何使用可变参数的计数功能的单一功能的指针数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆