Callbacks in C++


separate client and server interface specifications

//----------------------------------------
// l i b r a r y c o d e 
//----------------------------------------
template <class P1>
class Callback1Base
{
public:
  virtual void operator()(P1) const = 0;
  virtual Callback1Base<P1>* clone() const = 0;
};
//----------------------------------------
template <class P1, class Client, class Member>
class Callback1:
  public Callback1Base<P1>
{
public:
  Callback1(Client& client_, Member member_):
    _client(client_), 
    _member(member_)
  {}

  /*virtual*/ void operator()(P1 parm_) const
  {((&_client)->*_member)(parm_);}

  /*virtual*/ Callback1<P1,Client,Member>* clone() const 
  {return new Callback1<P1,Client,Member>(*this);}
private:
  Client& _client;
  Member _member;
};
//----------------------------------------
class Button
{
public:
  Button(Callback1Base<Button*>& callback_):_pCallback(callback_.clone()){}
  ~Button() {delete _pCallback;}
  void push() {(*_pCallback)(this);}

private:
  Callback1Base<Button*>* _pCallback;
};
//----------------------------------------
// 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;
  Callback1<Button*,CdPlayer, void (CdPlayer::*)(Button*)> 
    playCallback(aCdPlayer,&CdPlayer::playButtonPushed);
  Callback1<Button*,CdPlayer, void (CdPlayer::*)(Button*)> 
    stopCallback(aCdPlayer,&CdPlayer::stopButtonPushed);

  Button playButton(playCallback);
  Button stopButton(stopCallback);

  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