Untitled

Started by
5 comments, last by Oluseyi 18 years, 9 months ago
i want to have a pointer to a function, so i have the following:

class MyClass()
{
   class MyMod()
   {
      typedef void(*PointFn)();

      PointFunc myfunction;
   };

   void Init(MyMod::PointFn afunction);
}

...

void MyClass::MyMod::Init(MyMod::PointFn afunction)
{
   // do stuff
}



// now this calls the Init function:
// assume i have a StandAloneBig() and a AnotherClass::Big() defined...

void StandAloneBig()
{
  // not in class
}


void AnotherClass::Big()
{
  // funcyion in class
}


// from within AnotherClass class, i call:


CMyClass.Init(&Big);  // doesnt work

// but:

CMyClass.Init(&StandAloneBig);  // does work


any ideas how i can get the pointer to the AnotherClass::Big function? error i get is:

error C2664: 'MyClass::MyMod::Init' : cannot convert parameter 2 from 'void(__thiscall AnotherClass::* )(void)' to 'MyClass::MyMod::Init'


Advertisement
A function pointer must be generated by a static function, otherwise the compiler can't get the address...
so you have two ways:
- the direct approach declare the function static in Big
- or create a capsulation...


in the form
class BigCbProxy
{
static void function( void* clientData )
{
//now you must get to big...
static_cast<Big*>(clientData)->Big();
}
}

I hope this helps
Quote:Original post by Sparhawk42
A function pointer must be generated by a static function, otherwise the compiler


Not quite true. You can get and use pointers to member functions as well. However, it is true that the two are not interchangeable.
ahh! i must have not put static on the definitions (i thought they were static but they were not!); it does now compile.

But, its possible i may not want them static in future....
yes i need it NOT to be static.... any ideas?
Then it becomes:

typedef void (MyClass::*PointFunc)();

assuming the function is in MyClass. You have to include the name of the class the function is in (or using a templated function).

Then, to invoke the function, you need an instance (that's why you didn't make your function static, now didn't you?), and call:

PointFunc myfunction;
instance.*myfunction();
Quote:Original post by bilstonwarrior
yes i need it NOT to be static.... any ideas?
Use a function object:
struct A{  ...  struct FunctionObj  {    ...    void operator () ()    {      ...    }    ...  };  ...  FunctionObj * fn;};A a;A::FunctionObj f;a.fn = &f;*(a.fn)();        // dispatcha.fn->operator(); // dispatch

For cleaner dispatch syntax, eliminate the pointer indirection.

This topic is closed to new replies.

Advertisement