Hello,
thank you for your answers.
Eric:
Quote:
|
Have a look at boost::function
|
gpd:
Quote:
As the exact result type of 'bind' is unspecified (well, you can see
it in the error message, but you shouldn't rely on it), you will have
to use boost::function as the type of the 'function' member of
oneVar_function: [...]
|
I implemented my (wanna-be) callbacks as boost::function instead of
function pointers, and the two problems I mentioned in my previous
post are gone.
Furthermore I feel that switching the whole design of my real code
to boost::function will be straightforward. Cool!
Here is the modified version of my toy example, which compiles
and works fine:
// ---------------- this is the file function2.cpp
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
struct oneVar_function // one variable function
{
boost::function<double (double x, void* params)function;
void* params;
};
struct twoVar_function // two variables function
{
boost::function<double (double x, double y, void* params)function;
void* params;
};
double
my_function (double x, double y, void* params)
{
// I cast `params` to double*.
// The user will be kind enough to always
// give a double* as 3rd argument when
// calling my_function.
double* alpha = static_cast<double*>(params);
return x + y + *alpha; // or whatever
}
int main()
{
double alpha = 3;
twoVar_function f;
oneVar_function g;
f.function = &my_function;
f.params = α
double a_given_number = 2;
g.function = boost::bind(f.function,
_1,
a_given_number,
_2);
g.params = α
std::cout << (f.function)(1, 2, f.params) << std::endl;
// expected: 6
std::cout << (g.function)(1, g.params) << std::endl;
// expected: 6
/*
* bash-3.00$ g++ function2.cpp
* bash-3.00$ ./a.out
* 6
* 6
* bash-3.00$
*/
}
// ---------------- end of file function2.cpp