C++ Publish Subscribe

I had the need to make a publish-subscribe mechanism in C++. So as is common, I looked around at other examples to see how others have done it and found a simple example courtesy of GitHubGist user makomweb.

His didn’t include comments, so I’m commenting it on my own copy here.

As programmers, we learn from each other. Each piece of code we write or see helps us to reason, adjust, and form opinions.

Getting our hands dirty and coding is a great learning experience. But reviewing the code of others helps us to build skills.

Why did makomweb not just have the Subscriber class conform to an interface? The entire class could have been passed to the Producer instead of just saving off the method. Think about it.

Look at the Publisher.Publish method. Elegant. One line of code to call Event(). The magic happens in Event.operator(). It calls the method that was registered in the Event.Subscribe call.

Had we stored an object that complies to an interface, we could do the same thing. We store the object in a map. When a “Publish” happens, we iterate the map, calling the method from the interface.

Leave a Reply

Your email address will not be published. Required fields are marked *