Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing events in C++

Tags:

c++

events

After some research on internet for an efficient way to implement events in C++, I found the following methods

  • Interface class - Applications can override the virtual functions in the derived class
  • Normal Callback mechanism using function pointers
  • Delegates using Boost.function
  • Signals and slots (as used in Qt)

I am confused on advantages and disadvantages of each of these and when to use anyone of this. Which is the best method and why? Is there any other solutions which are better than the ones listed?

like image 689
user761867 Avatar asked Dec 28 '22 19:12

user761867


1 Answers

FWIW, my vote would be for Boost Signals any day.

Boost ensures portability. Of course it integrates nicely with e.g. Boost Asio, Functional, Bind, etc.

Update:

Signals2

This documentation describes a thread-safe variant of the original Boost.Signals library. There have been some changes to the interface to support thread-safety, mostly with respect to automatic connection management. [....]

Boost ensures portability. Of course it integrates nicely with e.g. Boost Asio, Functional, Bind, etc.

boost::signals2::signal sig;

sig.connect(&print_sum);
sig.connect(&print_product);
sig.connect(&print_difference);
sig.connect(&print_quotient);

sig(5., 3.);

This program will print out the following:

The sum is 8
The product is 15
The difference is 2
The quotient is 1.66667

sample actions:

void print_sum(float x, float y)
{
  std::cout << "The sum is " << x+y << std::endl;
}

void print_product(float x, float y)
{
  std::cout << "The product is " << x*y << std::endl;
}

void print_difference(float x, float y)
{
  std::cout << "The difference is " << x-y << std::endl;
}

void print_quotient(float x, float y)
{
  std::cout << "The quotient is " << x/y << std::endl;
}
like image 52
sehe Avatar answered Jan 05 '23 22:01

sehe