[英]Array of functions with built in arguments in C
Say I have these two functions and a definition of an array of these two functions:假设我有这两个函数和这两个函数的数组的定义:
int flag;
int add(int a, int b){
return a+b;
}
int multiply(int a, int b){
return a*b;
}
typedef int(*f)(int, int);
f func_array[2] = {&add, &multiply};
Now, there is a specific place in my code that I want to call these two functions depending on my flag state with the same arguments each time .现在,我的代码中有一个特定位置,我想根据我的标志 state 调用这两个函数,每次都使用相同的 arguments 。
For example:例如:
int var;
if(flag == 0)
{
var = func_array[flag](1,1);
}
else{
var = func_array[flag](2,2);
}
Is there a way to define it inside the array itself?有没有办法在数组本身内部定义它? Somwhow defining the array like this and just call the function:
Somwhow 像这样定义数组并调用 function:
f func_array[2] = {&add(1,1), &multiply(2,2)};
int var = func_array[flag]();
Is this a valid way?这是一种有效的方式吗? Is there any more elegant way to do it?
有没有更优雅的方法来做到这一点?
You can define a set of arrays for each parameter:您可以为每个参数定义一组 arrays:
#define ARR_SIZE 2
typedef int(*f)(int, int);
f func_array[ARR_SIZE] = {&add, &multiply};
int param1_array[ARR_SIZE] = { 1, 2};
int param2_array[ARR_SIZE] = { 1, 2};
The call would become电话会变成
if(flag < ARR_SIZE)
{
int var = func_array[flag](param1_array[flag], param2_array[flag]);
}
I just added a check on the array size.我刚刚添加了对数组大小的检查。
With a macro用宏
#define flag_call(flag) \
func_array[flag](param1_array[flag], param2_array[flag])
you could simplify it even more你可以更简化它
if(flag < ARR_SIZE)
{
flag_call(flag);
}
Not sure what the point is but you can do this:不知道重点是什么,但你可以这样做:
int add11(void){ return add(1,1); }
int multiply22(void){ return multiply(2,2); }
/*skipped the new typedef*/
int (*func_array2[2])(void) = {&add11,&multiply22};
https://godbolt.org/z/ejMn4n https://godbolt.org/z/ejMn4n
The wrappers could even be inlinable if you make the array static
or auto
.如果您制作数组
static
或auto
,包装器甚至可以是内联的。
You can use a struct to bundle them together:您可以使用结构将它们捆绑在一起:
typedef int(*f)(int, int);
struct func_and_args {
f func;
int a;
int b;
}
... ...
struct func_and_args arr[] = {{&add,1,1},{&multiply,2,2}};
int var = arr[flag].func(arr[flag].a,arr[flag].b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.