Category Archives: Posts

Observable C++ expressions – using the Observable library

The Observable C++ library has a new feature: observable expressions.

You can create an expression out of observable values and properties, and its result will also be an observable value. The result will stay updated when the expression’s operands change.

A simple example

Some more details

Observable expressions are just like regular C++ expressions, except that instead of being evaluated only once, they are evaluated each time one of their operands changes.

Take the following code:

This is just some regular C++ code; it will compute the average of two numbers. We’ve all seen this kind of code before and we all know how it works.

It works, but what if your operands change? Well, obviously, we’ll need to recompute the average!

See, easy! We just need to create a function that computes an average, and each time we change one number we call that function and update the average.

Let’s try it with the Observable library, using observable values:

The new code is much simpler, right?

You can also subscribe to changes and get notified when the avg changes.

The library supports much more complex expressions than our simple average. You can use mathematical functions, select between two values and even create your own functions (called filters).

Check out the expression documentation for more examples and a more detailed explanation.

How this works, from 10k feet

The quick and simple explanation is this: the library provides overloaded operators for value<T>s.

When you use observable values, the overloaded operators return intermediate expression nodes (which also overload the operators).

These expression nodes form an expression tree that can be used to evaluate an arbitrary expression.

The root of this tree is passed to another class, an expression class, which knows how and when to evaluate the expression tree.

The observe() function takes an expression tree and returns an observable value that is linked to an expression. This observable value is updated each time the expression is evaluated.

When you should use observable expressions

If you can tolerate a bit of template machinery behind the scenes, and you want to use a reactive approach to your code, then this is for you.

Observable expressions can simplify your code and they can make it more readable than the equivalent code.

Check out the Capture The Dot Game and see how observable expressions are used with Qt.

Check out the Observable library on GitHub:

Implementing the observer pattern

The Observable C++ library – implementing the observer pattern

TL;DR: Use the Observable C++ library if you need to implement the observer pattern for your C++ project.

Why you should use this library

Whenever I need to subscribe to events, I usually implement some variation of the observer pattern, or (if available) hack and misuse Qt’s signals and slots mechanism to do the job. Because of this, usually I’m not happy with the results; especially if I misuse QObjects.

I hope that we can all agree that using a library is a lot easier than rolling your own. It should also be a lot better than hacking other libraries.

The library is header-only, so you can easily integrate it into your project. If you want to build the tests, they’re using CMake, so that should be easy too.

It works with Microsoft Visual Studio 2015+, GCC 5.4+ and Clang 3.6+ on both Windows and Linux.

Some trivial observer examples

The most basic code that you can write will be using a subject object directly:

Subjects take a “function type” as their template parameter. You can subscribe to notifications using any callable object that can be stored inside a std::function<FunctionType>.

The subscribe() method returns a subscription object. You can keep the subscription object, to use later for unsubscribing, or you can call the release() method and make the subscription live forever.

Subjects also have some code that makes sure you don’t crash if you call unsubscribe() after the subject instance is destroyed.

Your only concern will be to keep the “observer” callable valid while it remains subscribed.

You can also use observable properties:

Properties use subject objects behind the scenes, so everything from above will also apply.

Property setters are private, and by giving the enclosing class as a template parameter, you’ll be able to access the assignment operator. Because of this, properties are more like methods than member variables (and it also makes it much easier to pass code reviews).

Why not just use Boost.Signals2 or Qt?

Boost.Signals2 and Qt are pretty cool libraries and do their jobs well.

This library is not meant to replace signals and slots; it focuses more on providing easy to use observable properties while not being invasive – see the MOC or the limitation on multiple inheritance for QObjects.

Choose whichever library works best for your case; you can even choose them both (for example, have your models use this library and your views use Qt).

Where to get the Observable library

Check out the library’s GitHub page.

There’s also some basic documentation on GitHub.

The Observable library is licensed under the Apache 2 license.

Any bug reports, feature requests, questions or code contributions are welcome.

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:

12345.6 +

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:

12345.6 +
12345.65123 +

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

    0.05123 +
    0.10246 +

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:

Starting: /home/daniel/projects/floats/build/floats
2916.660400390625 <- Reverse sorted
3057.517578125 <- Normal sum
3192.88330078125 <- Sorted
3194.340576171875 <- Kahan summation
3194.340576171875 <- FPU
3194.340576171875 <- Double truncated
3194.34058601572951374691911041736602783203125 <- Double precision

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.