Passing functions with some arguments included
In mathematics, if I have a function f(x, y, z) in three variables, I can define a new function g(x) by passing f the variable x and two fixed values. For example, g(x) = f(x, 2, 5).
Can I do this with function pointers in C++? If I have a pointer *f pointing to a function which takes two arguments, can I somehow pass one argument along with the pointer, and use f as a unary function?
Here is some faulty code showing what I'd like to do. add() is defined as taking two ints, but in main() I would like to pass it to apply_function() with one of the two ints already specified.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int apply_function(int x, int (*f)(int)) {
return f(x);
}
int main() {
cout<<apply_function(2, add(, 3));
}
My thanks for any help anyone could provide.
# 2 Re: Passing functions with some arguments included
If you have no access to the source code of apply_function, you can still define the add3 function like that:
int add3(int a) {
return add(a, 3);
}
And then, pass add3.
If the value 3 is actually variable, then you should use the context argument the librairy provides, if it provides one.
A C library needing Callbacks and not providing any context parameter has a flawed design.
However, it is still possible to make it work: Passing data in Thread Local Storage that you set just before the callback function call, or a global variable if the context data is global to the whole process.
Under Win32, thread local storage can be accessed through TlsAlloc/TlsSetValue/TlsGetValue/TlsFree, and under some UNIX systems pthread_key_create/pthread_setspecific/pthread_getspecific/pthread_key_destroy.