Using C++ templates for size-based type selection

The standardisation of size-specific integer types in C/C++ is extremely useful for portability. That is, when you use types like uint16_t and int32_t, you know exactly what size of data type you’re getting (assuming your compiler supports it, which is usually the case unless you’re working with very specialist/embedded systems). This isn’t the case with the more traditional types like short and int whose sizes can vary from one compiler to another. However, the size is obviously part of the type name, meaning you need to alter declarations directly if you want to use a type of a different size.

Using the std::conditional template from C++11 lets you change this. Instead, you can have a template parameter which specifies the size you want (e.g. in bytes). The corresponding type declaration can be automatically deduced from there.
Read more Using C++ templates for size-based type selection

Dynamic types in C++: factories, templates, or lots of switches?

While doing some C++ programming today, I was faced with a design decision. My code had to be able to create and delete objects of various types, dynamically and on-demand at run-time. Easy if you’re working with a loosely-typed language such as PHP, but it’s a different story when you’re working with C++. The actual range of classes which could be created is fixed at compile-time, so there are still lots of possibilities, ranging from the very simplistic multi-way decisions, through to some downright groovy template shenanigans. Yes. I just said groovy. That’s how brilliant a good bit of template programming can be!
Read more Dynamic types in C++: factories, templates, or lots of switches?