Hi all. I wonder if you have an answer for me for this curious little pointer problem. I have an all purpose function that I typically pass a function to. I'm having to pass it a function from someone else's struct and I can't seem to figure out how to do it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
struct someStruct{
int someStructFunction(int x){
return ( x + 1 );
}
}
int myCoolFunction(int(*someFunction)(int)){
return ( someFunction(5) * 2 );
{
void main{
int the_result;
someStruct structInstance;
the_result = myCoolFunction( structInstance.someStructFunction );
return 0;
}
What I get when I compile though is
error: argument of type 'int (someStruct::)(int)' does not match 'int (*)(double)
' Perhaps I should change my function-passing system or something but I can't seem to figure it out. Any ideas? Thanks!
Functions from a class are different from functions in the global space:
1 2 3 4 5
//notice the someStruct::
//also note you need an object since the function is not static
int myCoolFunction(someStruct obj, int (someStruct::*someFunction)(int)) {
return (obj->(*someFunction)(5) * 2); //don't forget to deference the function pointer before calling it
}
To add to the above, to solve your problem you need either std::mem_fun and std::bind1st, or boost::bind and boost::function. I prefer the latter as being easier to read.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <boost/bind.hpp>
#include <boost/function.hpp>
struct someStruct {
int memfunc( int x ) const
{ return x + 1; }
};
int free_func( int x )
{ return x + 2; }
int call_it( const boost::function<int(int)>& fn )
{ return fn( 5 ) * 2; }
int main() {
someStruct inst;
int result = call_it( boost::bind( &someStruct::memfunc, &inst, _1 ) );
int result2 = call_it( free_func );
}