Callbacks in C++


handle body

//----------------------------------------
// l i b r a r y c o d e 
//----------------------------------------
template <class P1>
class Base_Callback1Body
{
public:
  virtual ~Base_Callback1Body() {}
  virtual void operator()(P1) const = 0;
  virtual Base_Callback1Body<P1>* clone() const = 0;
};
//----------------------------------------
template <class P1>
class Callback1
{
public:
  Callback1(Base_Callback1Body<P1>* body):
    body_(body)
  {}

  Callback1(const Callback1<P1>& callback):
    body_(callback.body_->clone())
  {}

  ~Callback1() {delete body_; body_ = 0;}
  Callback1<P1>& operator=(const Callback1<P1>& callback)
  {
    if (this != &callback)
    {
      delete body_;
      body_ = callback.body_->clone();
    }
    return *this;
  }

  void operator()(P1 p1) {(*body_)(p1);}

private:
  Base_Callback1Body<P1>* body_;
};
//----------------------------------------
template <class P1, class Client, class Member>
class Member_Callback1Body:
  public Base_Callback1Body<P1>
{
public:
  Member_Callback1Body(Client& client_, Member member_):
    _client(client_), 
    _member(member_)
  {}

  /*virtual*/ void operator()(P1 parm_) const
  {((&_client)->*_member)(parm_);}
  /*virtual*/ Member_Callback1Body<P1,Client,Member>* clone() const 
  {return new Member_Callback1Body<P1,Client,Member>(*this);}

private:
  Client& _client;
  Member _member;
};
//----------------------------------------

template <class P1, class Client, class Member>
Callback1<P1>
make_callback(Callback1<P1>*, Client& client_, Member member_)
{
  return Callback1<P1>
  (
    new Member_Callback1Body<P1,Client,Member>(client_,member_)
  );
}
//----------------------------------------
class Button
{
public:
  Button(const Callback1<Button*>& callback_):_callback(callback_){}
  ~Button() {}
  void push() {_callback(this);}

private:
  Callback1<Button*> _callback;
};
//----------------------------------------
// c l i e n t c o d e
//----------------------------------------
#include <iostream.h>
class CdPlayer
{
public:
  void playButtonPushed(Button*) {cout << "PLAY" << endl;}
  void stopButtonPushed(Button*) {cout << "STOP" << endl;}
};
//----------------------------------------
main()
{
  CdPlayer aCdPlayer;
  Button playButton
  (
    make_callback
    ((Callback1<Button*>*)0, aCdPlayer, &CdPlayer::playButtonPushed)
  );

  Button stopButton
  (
    make_callback
    ((Callback1<Button*>*)0, aCdPlayer, &CdPlayer::stopButtonPushed)
  );

  playButton.push();
  stopButton.push();

  return 0;
}

[View/Add Comments]


Callbacks in C++
Copyright © 1996-2000 Paul Jakubik
Created: 26 July 1996. Last update: 26 November 2000.
pauljakubik@yahoo.com