Emulating the static initialization blocks of Java in C++

What is a static initialization block?

In Java, there is a language construct called a static initialization block. The static initialization block will be called the first time the class is loaded by the Java runtime. For example, consider the following code snippet1:

Continue reading


  1. The highlighting in this code snippet is different because highlight.js had problems with this rarely used construct. As a workaround, I used a GitHub Gist for displaying this snippet. 

Rarely known C++ constructs (part 1): Function try blocks

C++ has some language constructs that are rarely seen in use. These constructs have their own, valid uses, but should be used sparingly. As the now adage-status quote from The Old New Thing says:

Code is read much more often than it is written, so plan accordingly

In this series we will take a look at different instances of unusual C++ language constructs, shortly explaining their use-cases, syntax and pitfalls.

UPDATE: the series was moved to Dr. Dobbs! The rewritten, expanded first part is available here.

Implementing a code generator with libclang

[DOI: 10.5708/szelei.2014.A.1]

Introduction

Click here to skip the introduction and see the code.

The following article covers the process of implementing a practical code generator for C++ in detail. You can find the full source code for the article on GitHub.

A code generator is a very useful asset in a larger C++ project. Due to the lack of introspection in the language, implementing the likes of reflection, script binding and serialization requires writing some sort of boilerplate that essentially keeps the data which is otherwise thrown away by the compiler. These solutions are either intrusive (heavily macro-based, thus hard to debug and require weird syntax in declarations) or fragile (the boilerplate must be constantly updated to follow the actual code, and might break without warning). One way to improve the robustness is to automate writing this boilerplate. In order to achieve this, we need to parse the code somehow, in other words, understand what information to keep. However, parsing C++ is an extremely complex task, and with the copious amount of weird corner cases, we are in for quite a ride if we attempt to do so. Continue reading