Boost logo

Boost Users :

Subject: [Boost-users] Using boost to eliminate an ugly facade function
From: Chris Stankevitz (chrisstankevitz_at_[hidden])
Date: 2012-08-29 14:24:06


Hello,

Can boost help me eliminate the ugly facade function I use below? I
have a boost::signals2::signal that passes an object ("CPerson").

I want to connect to this signal not to receive the object ("CPerson")
but to receive the result of one of its methods ("CPerson::GetAge()").
 Can boost help me with this? If so I'm eager to read and learn about
it, I just need to know what it is called.

Thank you!

Chris

//===

#include <boost/signals2/signal.hpp>

//----------
// A CPerson offers GetAge()
//----------
struct CPerson
{
  int GetAge() const { return 0; }
};

//----------
// A CCompany has a boss and a signal
// to tell when boss is hired
//----------
struct CCompany
{
  CPerson GetBoss() const { return mBoss; }

  boost::signals2::signal<void(const CPerson&)> BossHired;

  CPerson mBoss;
};

//----------
// A CProcessor processes int ages.
// It does not know aobut CPerson
//----------
struct CProcessor
{
  void f(int Age) {}
};

//----------
// ProcessorFacade is used to strip
// an age of a CPerson before
// passing the age to CProcessor
//----------
void ProcessorFacade(CProcessor& Processor, const CPerson& Person)
{
  Processor.f(Person.GetAge());
}

//----------
// main puts it all together
//----------
int main()
{
  CCompany Company;

  CProcessor Processor;

  // Compiler error: the signal sends an instance of CPerson,
  // not the result of CPerson::GetAge(). Too bad because
  // CProcessor does not have know about CPerson
  //
  // Company.BossHired.connect(
  // boost::bind(&CProcessor::f, &Processor, _1));

  // So we use an ugly facade instead
  Company.BossHired.connect(
    boost::bind(ProcessorFacade, boost::ref(Processor), _1));

  return 0;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net