views:

300

answers:

5

Hello,

I have created a Timer class that must call a callback method when the timer has expired. Currently I have it working with normal function pointers (they are declared as void (*)(void), when the Elapsed event happens the function pointer is called.

Is possible to do the same thing with a member function that has also the signature void (AnyClass::*)(void)?

Thanks mates.

EDIT: This code has to work on Windows and also on a real-time OS (VxWorks) so not using external libraries would be great.

EDIT2: Just to be sure, what I need is to have a Timer class that take an argument at the Constructor of tipe "AnyClass.AnyMethod" without arguments and returning void. I have to store this argument and latter in a point of the code just execute the method pointed by this variable. Hope is clear.

+3  A: 

The best solution I have used for that same purpose was boost::signal or boost::function libraries (depending on whether you want a single callback or many of them), and boost::bind to actually register the callbacks.

class X {
public:
   void callback() {}
   void with_parameter( std::string const & x ) {}
};
int main()
{
   X x1, x2;
   boost::function< void () > callback1;

   callback1 = boost::bind( &X::callback, &x1 );
   callback1(); // will call x1.callback()

   boost::signal< void () > multiple_callbacks;
   multiple_callbacks.connect( boost::bind( &X::callback, &x1 ) );
   multiple_callbacks.connect( boost::bind( &X::callback, &x2 ) );
   // even inject parameters:
   multiple_callbacks.connect( boost::bind( &X::with_parameter, &x1, "Hi" ) );

   multiple_callbacks(); // will call x1.callback(), x2.callback and x1.with_parameter("Hi") in turn
}
David Rodríguez - dribeas
But isn't boost an external library?
futureelite7
Yes, they are not part of the standard, but boost is the most standard non-standard library you will find.
David Rodríguez - dribeas
Besides, `function` and `bind` will be added to the C++0x standard library (may be already available in `std::tr1` namespace).
UncleBens
+1  A: 

boost::function looks like a perfect fit here.

Nikolai N Fetissov
He said no external libraries.
John Dibling
Oh, missed that :) Please note that boost::function is header-only library, so no link dependencies.
Nikolai N Fetissov
+2  A: 

Maybe the standard mem_fun is already good enough for what you want. It's part of STL.

Maurits Rijk
Let me check it. Looks good.
SoMoS
I proposed boost::function as I was assuming that the Timer would be a non-templated class that had to keep the callback for later use. Since mem_fun is templated, either you teplate the timer class on the class of the callback, or else you will have to wrap the mem_fun in a non-templated class, and here is where you end up implementing boost::function yourself...
David Rodríguez - dribeas
+3  A: 

Dependencies, dependencies... yeah, sure boost is nice, so is mem_fn, but you don't need them. However, the syntax of calling member functions is evil, so a little template magic helps:

   class Callback
   {
   public:
      void operator()() { call(); };
      virtual void call() = 0;
   };

   class BasicCallback : public Callback
   {
      // pointer to member function
      void (*function)(void);
   public:
      BasicCallback(void(*_function)(void))
          : function( _function ) { };
      virtual void call()
      { 
          (*function)();
      };
   };   

   template <class AnyClass> 
   class ClassCallback : public Callback
   {
      // pointer to member function
      void (AnyClass::*function)(void);
      // pointer to object
      AnyClass* object;        
   public:
      ClassCallback(AnyClass* _object, void(AnyClass::*_function)(void))
          : object( _object ), function( _function ) { };
      virtual void call()
      { 
          (*object.*function)();
      };
   };

Now you can just use Callback as a callback storing mechanism so:

void set_callback( Callback* callback );
set_callback( new ClassCallback<MyClass>( my_class, &MyClass::timer ) );

And

Callback* callback = new ClassCallback<MyClass>( my_class, &MyClass::timer ) );

(*callback)();
// or...
callback->call();
Kornel Kisielewicz
Ok, take in mind that I do not understand almost nothing here. C++ is not what I use to work with, I just need to do some changes to a running project so I expect to avoid understanding all of this magic.How can I execute the callback? If I just put callback(); i get a term does not evaluate to a function taking 0 arguments.Thanks in advance.
SoMoS
And the class BasicCallback looks like is not used anywhere. Maybe there is a mistake there?
SoMoS
@SoMoS, BasicCallback allows you to use the same interface with your old callbacks -- it doesn't take a class. You did get your error because you tried to "execute" a pointer, `(*callback)()` would be the proper call. I modified my code a little and added a explicit `call` method, maybe that will be clearer.
Kornel Kisielewicz
Thanks, (*callback)() is enough for me. You help has saved me a ton of hours. Thanks a lot.
SoMoS
@SoMoS, my pleasure :)
Kornel Kisielewicz
A: 

I'm assuming an interface like this:

void Timer::register_callback( void(*callback)(void*user_data), void* user_data );

template<typename AnyClass, (AnyClass::*Func_Value)(void)>
void wrap_method_callback( void* class_pointer )
{
   AnyClass*const self = reinterpret_cast<AnyClass*>(class_pointer);
   (self->*Func_Value)();
}

class A
{
public:
   void callback()
   { std::cout << m_i << std::endl; }
   int m_i;
};

int main ()
{
   Timer t;
   A a = { 10 };
   t.register_callback( &wrap_method_callback<A,&A::callback>, &a );
}

I think a better solution would be to upgrade call you callback to either use boost::function or a homegrown version (like Kornel's answer). However this require real C++ developers to get involved, otherwise you are very likely to introduce bugs.

The advantage of my solution is that it is just one template function. Not a whole lot can go wrong. One disadvantage of my solution is it may slice your class with cast to void* and back. Be careful that only AnyClass* pointers are passes as void* to the callback registration.

caspin