Hi everybody!
I'm new to this forum, and I hope i won't make mistakes posting my question.
I got stuck on a problem: how can I pass a function to another function, but without knowing in advance how many variables will the last one have?
I built a program that finds the roots of a particular function, something like:
1 2 3 4 5
|
void find_roots(double &x, vector<double> &V) {
double f = 2*x*x; //for example
.....find roots of f with a bisection method.....
.....put the roots in vector V.....
}
|
I was trying to generalize it, so that i could pass a function as a parameter instead of defining it in the inside.
If I'm not mistaken this can be done in a couple of ways, for example:
1 2 3
|
void find_roots(double my_function(double), vector<double> &V) {
.....find roots and put them in V.....
}
|
or:
1 2 3
|
void find_roots(double (*my_function)(double), vector<double> &V) {
.....find roots and put them in V.....
}
|
Anyway, both want to know how many parameters (and their type) will the function parameter "my_function" have.
Instead, i'd like to pass ANY kind of function, also:
where y and z are parameters defined in another part of the main() program (not outside main()). For example:
1 2 3 4 5 6 7 8 9 10 11
|
void find_roots(???, vector<double> V) {
.....find and put them in V.....
}
int main() {
double y = 5.2;
double z = 1;
vector<double> roots;
find_roots(/*somehow my function*/, V);
return 0;
}
|
Achieving this, I could reuse the find_roots method in many other occasions.
Is this possible in a simple manner?
Thanks a lot in advance!
P.S. I'm quite new it C++ code, so if there's any smarter way of doing this task i'd be thankful for any suggestion!