Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Boost signal example 2: emitting this

 

This Boost signal example shows how to emit this.

 

 

 

 

 

 

Technical facts

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: CppBoostSignalExample2.pro

 

#-------------------------------------------------
#
# Project created by QtCreator 2011-08-12T10:26:40
#
#-------------------------------------------------
QT       += core
QT       -= gui
TARGET = CppBoostSignalExample2
CONFIG   += console
CONFIG   -= app_bundle
TEMPLATE = app
SOURCES += main.cpp

 

 

 

 

 

main.cpp

 

#include <iostream>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/signals2.hpp>

struct Thing
{
  Thing(const int id) : m_id(id) {}
  boost::signals2::signal<void (const Thing*)> m_signal;
  const int m_id;
  void EmitMe() const { m_signal(this); }
};

struct Manager
{
  Manager()
  {
    for (int i=0; i!=5; ++i)
    {
      boost::shared_ptr<Thing> t(new Thing(i));
      //Do not forget the placeholder!
      t->m_signal.connect(boost::bind(&Manager::OnSignal,this, boost::lambda::_1));
      m_v.push_back(t);
    }
  }
  void EmitRandom()
  {
    const int i = std::rand() % 5;
    m_v[i]->EmitMe();
  }

  private:

  std::vector<boost::shared_ptr<Thing> > m_v;

  void OnSignal(const Thing* thing)
  {
    std::cout << thing->m_id << '\n';
  }
};

int main()
{
  Manager m;
  for (int i=0; i!=10; ++i) m.EmitRandom();
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict