Reputation: 963
Is there a way to pass member function as a parameter to a global function ? I found this but it doesn't really solve my problem.
Lets say that I have following global functions:
double Function(double (*fEval)(double F1, double F2),double min, double max,int numArgs,...);
bool Function2(double (*fEval1)(double F1, double F2),double (*fEval2)(double F1, double F2),double xmin, double xmax, double ymin, double ymax,double &ax, double &ay,int numArgs,...);
and one of my member functions calls Function2 as
Function2(&F1, &F2, 0, m_m1, 0, m_m2, &m_n1, &m_n2,0);
Where F1 and F2 are member functions and Function2 calls somewhere Function1 but at the moment my problem is with Function2 and how to declare it correctly.
Okay now I've managed to change my function declaration to
bool Function2(double (CLASS::*)(double F1, double F2),double (CLASS::*)(double F1, double F2),double xmin, double xmax, double ymin, double ymax,double *ax, double *ay,int numArgs,...)
And I have probably only one problem which occurs when I'm trying to call the functions fEval1 and fEval2 which have been replaced with CLASS::* so how I can call the first and second member functions within this function ?
Upvotes: 3
Views: 251
Reputation: 490108
It's sort of possible to do this, but it's open to a lot of question whether it's what you really want to do.
There is such a thing as a pointer to a member function, but it acts as basically an offset within a struct, so to use it you need to supply both the pointer to the member function, and an object on which to invoke that member function. Given what you're doing, it looks unlikely (at least to me) that you really want this.
My immediate reaction would be to write your Function1
and Function2
as templates, and pass functors instead of pointers to functions. Instead of specifying a normal member function, each will do like other functors, and overload operator()
to do the work.
Edit: I'd also avoid using variadic functions if you can -- they throw away type information, which is one of the definite no-nos in C++. Especially with new C++ compilers that support C++11, it's almost always pretty easy to avoid it (you can pass an initializer list that creates an object instead).
Upvotes: 4
Reputation: 6110
Member function pointers are different to ordinary function pointers - you need to specify their class as part of the type. Also, when calling them, you need to specify an object for which the member function is called.
Your error message shows that the type of member-function which you're passing is in fact double (CLASS::*)(double, double)
- this isn't compatible with the ordinary function pointer type in the signature
Have a look at the C++ FAQ here for a bit more information on how to use member function pointers:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html
Upvotes: 4