windmaomao
12-10-2004, 12:43 PM
I am not sure if anyone has already posted it but i am sure it's not new to lot of programmers.
For example, if you want to integrate arbitary function, you define a function type float (*func)(float), and you pass it to your integration algorithm. This is very general and easy approach except that when you need to pass extra variables into the algorithm. This is when trouble starts. Usually, as NR does, we define a GLOBAL variable.
But no insult to fortran people, this global variable approach is very bad design.
Recently i just found there's a better way doing this by using the Boost::function and Boost::bind. Here's one example
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
class A {
public:
float constant;
A(): constant(0.2) {}
float func(A* a, float x) { return a->constant+x; }
};
int main()
{
using namespace std;
boost::function<float (A*,float) > f;
A a;
f=boost::bind(&A::func,&a,_1,_2);
cout << f(&a, 0.3);
int b;
cin >> b;
return 0;
}
For clarity, the idea is that now you can use f to call any function (has to be declared type) inside any class or struct and at the same time be able to access the data inside that class.
For more example, check the manual in http://www.boost.org/libs/libraries.htm
Best regards
Fang
For example, if you want to integrate arbitary function, you define a function type float (*func)(float), and you pass it to your integration algorithm. This is very general and easy approach except that when you need to pass extra variables into the algorithm. This is when trouble starts. Usually, as NR does, we define a GLOBAL variable.
But no insult to fortran people, this global variable approach is very bad design.
Recently i just found there's a better way doing this by using the Boost::function and Boost::bind. Here's one example
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
class A {
public:
float constant;
A(): constant(0.2) {}
float func(A* a, float x) { return a->constant+x; }
};
int main()
{
using namespace std;
boost::function<float (A*,float) > f;
A a;
f=boost::bind(&A::func,&a,_1,_2);
cout << f(&a, 0.3);
int b;
cin >> b;
return 0;
}
For clarity, the idea is that now you can use f to call any function (has to be declared type) inside any class or struct and at the same time be able to access the data inside that class.
For more example, check the manual in http://www.boost.org/libs/libraries.htm
Best regards
Fang