gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Is there a shorter way I can do this?

#118088 - LOst? - Sat Feb 10, 2007 12:26 am

Code:

template <typename X, typename Y, typename Z>
class A
{
protected:
void (A::*Hey) (A <X, Y, Z>* ptr);
};

template <typename X, typename Y, typename Z>
class B : public A <X, Y, Z>
{
private:
void OMG (B <X, Y, Z>* ptr)
{
}

public:
B ()
{
Hey = static_case <void A <X, Y, Z>::*) (A <X, Y, Z>*)> (&B <X, Y, Z>::OMG);
}

};


Anyway to make this shorter? Or to write a macro, function, or template that can do this in a better way?
Quote:

Hey = static_case <void A <X, Y, Z>::*) (A <X, Y, Z>*)> (&B <X, Y, Z>::OMG);


Thanks in advance :)
_________________
Exceptions are fun

#118091 - sajiimori - Sat Feb 10, 2007 1:45 am

Casting method pointers yields undefined behavior. Use virtuals, boost::function, or FastDelegate.

Edit: Here's an example using FastDelegate. I'm not sure why anyone would do this, but at least it's correct. (All the template stuff is irrelevant.)
Code:

template <typename X, typename Y, typename Z>
class A
{
protected:
   FastDelegate<void(A*)> Hey;
};


template <typename X, typename Y, typename Z>
class B : public A <X, Y, Z>
{
public:
   B()
   {
      Hey = FastDelegate<void(A<X, Y, Z>*)>(this, &B::OMG);
   }

private:
   void OMG(A<X, Y, Z>* aPtr)
   {
      // Dynamic cast needed because there's no way to guarantee
      // that a B pointer was provided to OMG.
      B* ptr = dynamic_cast<B*>(aPtr);
   }
};

#118152 - LOst? - Sat Feb 10, 2007 3:03 pm

sajiimori, thank you for your fast replay :)

I have looked into Delegate and other forms of tamplate hacks. It seems I have no wins by using any form of member function pointer here. I am going back to virtuals and switch case.

Else I wanted the best form of dynamic event processing possible.
_________________
Exceptions are fun