Implementing the observer pattern in C++

TL;DR use the observable library that I’ve created.

I recently needed to write some MVC code in C++ and, unfortunately, I needed to write everything almost from scratch.

The first thing I needed was a way to implement the observer pattern.

In that implementation I had access to Qt, so I used signals and slots to do a rudimentary implementation of observable models; Qt has one major drawback in this case: you cannot use virtual inheritance with QObject base classes.

Needles to say, my models got a bit messy.

I wrote a little library for this. You can find it on GitHub:

The most basic usage is a just a simple subject class:

Each subject has a “function type” as its template parameter and you can subscribe to notifications using any callable object that you can store inside a std::function<FunctionType>.

The subscribe method will return a subscription object which you can keep around to use later for unsubscribing, or you can call its release() method to keep the subscription around forever.

There’s some code that makes sure you don’t crash if you call unsubscribe after the subject is destroyed.

Your only concern is to keep the “observer” callable valid for as long as it remains subscribed.

If you want something a bit fancier, you can use properties:

Pretty nifty, if I do say so myself.

Same notes as above apply about lifetimes and the subscription object.

The weird second template parameter gets the class that is enclosing the property. It needs this so that it can become friends with your class and go out for beers… err, actually property setters are private and it marks whatever you pass to the second parameter as friend so that you can use the setters.

I’ll most likely use this in my next C++ project that needs observable objects.

I hope some of you find it useful too. If you do, watch or star the repo and if enough people find this interesting, I’ll be happy to turn this into a proper open source project.

Summing floats, more than one way to do it

So you summed some floats and have some unexpected results? Don’t be afraid, it’s normal.

When summing floats you have errors, not only because some numbers can’t be represented exactly as a float, but you get errors from differences in magnitude too.

Say you have a large float and add a small one to it, the small one will loose a lot of it’s precision in the process. You can see what can happen if you use fixed-width decimal numbers:

If you only have one addition, the error could be acceptable, but if you have to sum a lot of numbers the small ones could start to be a significant part of the sum, and that part can get lost in the process.

If you had:

You just lost .1, even if you could have avoided that by reordering the operations:

So what can you do?

Actually, you have multiple choices, depending on what you want to achieve:

  • You can sort the numbers (small to big) and sum them after sorting. This will group together numbers of similar magnitude and it will yield smaller errors. But this is not the best method, there are more accurate methods that will not need a sort.
  • You can use Kahan summation. This is more accurate than sorting and it should be faster too.
  • You can use use doubles. This is the best method, but what if you’re summing a vector of doubles in the first place?
  • If you’re feeling adventurous you can run the sum on the FPU, but not many places let you insert assembly in the codebase.

If you want to see some code, you can download this file: That code works on GCC 4.5 with the -std=c++0x flag.

Here is the output of a run, summing 10M random floats:

How to check if a type is a function

The first time I saw variadic templates, I knew they are useful (as useful as lambdas in my opinion).

Today, we’ll take a look at how to check if some type is a function or not.

Keep in mind that this is compile time code.

The code goes something like this:

This code is using template specialization on function types.

The variadic Args are there just so that we can catch any function, with any number of parameters.

If you want to use the value at runtime, there are a couple of ways to do it, one of them using the above code and decltype, and the one I’ll show you below, using the same method but function templates instead of structs.

That’s just the same thing, but using overloading instead of specialization.

You can use them like this:

where test_fun is defined like:

How to use Xdebug from behind a NAT

I don’t work with PHP any more, except when I have to maintain a huge code-base that runs only on a specific version of PHP, on a specific version of a specific Linux distro and from a specific directory using a specific… you get the picture.

I run this thing in a virtual machine and connect to it trough a VPN, so the only method to debug was print and error_log.

For a year I kept trying to connect Xdebug back to Netbeans (yes, in PHP the debugger connects to the IDE) and for a year I kept ignoring the obvious: ssh.

The beauty of this is in its simplicity: just go into your php.ini and set Xdebug to connect to localhost.

I assume the rest of the configuration is using defaults, like port 9000 and stuff.

Now, set up a reverse ssh tunnel to the server with port 9000 on both ends. Something like:
ssh -R 9000:localhost:9000 user@server. You can do this with Putty too.

You should now be able to debug the hell out of that code running on your specific… ok I’ll stop now.

Message dispatching in C++ (Part 1 – Type lists)

In the previous post, we’ve seen how not to do message dispatching.

Today we’ll build a type list.

If you remember we had an enum that held some sort of message id’s that can be used to select the proper class to unserialize on the receiving side. But what if you could do this:

and on the receiving side:

Continue reading

Message dispatching in C++ (Part 0 – Problem)

So you want to send a serialized class trough a socket? That’s not so hard, just use boost::serialization or even roll your own.

My question is: what do you do on the other end?

Let’s say you have some messages that you serialize somehow and send them trough a socket. On the other end you get some sort of buffer full of chars, how do you know what’s what, and which bytes correspond to which class?

Would you do this?

To send one of these things trough the socket you would have to write something like this:

So far so good, the only thing that’s bothering me is the enum, but maybe that’s just me.

Still with me? Great! Let’s look at the receiving side:

Hmm, that’s actually pretty horrible. And no matter what you do, no matter how many classes and design patterns you bury it under, some of it ugliness will still show trough in the end (I’m looking at you enum!).

What can we do to make this a little cleaner? The first thing we should do is get rid of that ugly enum. We can do that either by using RTTI or a type list.

I don’t like to depend on RTTI so I’ll go with the type list (a type list is a compile-time generic list of types).

For now, that’s it, but stay tuned, we’ll start to build a type list in the next part.