设置了一些参数的函数指针
Function pointer with some parameters set
我如何创建一个函数指针,指向一个函数,其中一些参数被设置为固定在定义上。
这是我的意思的一个例子:
假设我有函数
int add (int n, int m) {
return n+m;
}
和函数指针类型
typedef int (*increaser)(int);
我想要的是指向函数 add
的指针,它将第一个参数固定为 1 并使第二个参数保持打开状态。类似于
increaser f = &add(1,x);
我怎样才能做到这一点?
What I want is a pointer to the function add which fixes the first parameter to 1 and leaves the second paramenter open.
C 中没有这样的东西。最接近的方法是创建一个包装函数并指向它:
int add1(int x) {
return add(1, x);
}
increaser f = &add1;
如果不需要指向函数的指针,则可以使用宏:
#define increaser(x) add(1, (x))
C 不支持直接这样做。在 C++ 中有 std::function 和 bind 可以实现这一点。
None 对于纯 C 解决方案,您可以合理获得的最接近的是定义一个调用 add 的新函数,如:
int increment(int input) {
return add(1, input);
}
那么你可以这样做:
increaser f = &increment;
我如何创建一个函数指针,指向一个函数,其中一些参数被设置为固定在定义上。
这是我的意思的一个例子:
假设我有函数
int add (int n, int m) {
return n+m;
}
和函数指针类型
typedef int (*increaser)(int);
我想要的是指向函数 add
的指针,它将第一个参数固定为 1 并使第二个参数保持打开状态。类似于
increaser f = &add(1,x);
我怎样才能做到这一点?
What I want is a pointer to the function add which fixes the first parameter to 1 and leaves the second paramenter open.
C 中没有这样的东西。最接近的方法是创建一个包装函数并指向它:
int add1(int x) {
return add(1, x);
}
increaser f = &add1;
如果不需要指向函数的指针,则可以使用宏:
#define increaser(x) add(1, (x))
C 不支持直接这样做。在 C++ 中有 std::function 和 bind 可以实现这一点。
None 对于纯 C 解决方案,您可以合理获得的最接近的是定义一个调用 add 的新函数,如:
int increment(int input) {
return add(1, input);
}
那么你可以这样做:
increaser f = &increment;