Tag Archives: C++

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: main.zip. 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:

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.

QBash, displaying bash.org quotes with Qt and C++

What’s QBash?

A couple of days ago I started work on a small C++ app in the hope of learning a little bit more about Qt.

It took me about 4 hours to relearn C++ and get used to Qt. In the end I had a working app. Today, I polished it a little and managed to build it on Windows.

The app is small and useless. It gets a page from bash.org and displays one quote. You hit a button and it gets a new quote.

I thought it would be a nice project for learning Qt, because it uses networking, regular expressions and the Qt string class.

QBash running on KDE

The thing that impressed me with Qt, was that I was able to build the app on Windows without changing a single line of code. I expect that bigger apps will have some problems.

Get the code

As with all my little projects, you can have the code: qbash.tar.gz.

Now, don’t laugh. My C++ is a bit rusty, I haven’t used it in a couple of years. I’m still getting readjusted to manual memory management.