Replacing the Preprocessor in Modern C++

Back in the early days when the original C++ compiler compiled into C, it seemed natural to use the existing C preprocessor to add C (and C++) headers to each source file in order to create a coherent compilation unit. With the Standard Library available as a module in the C++23 standard, it’s time we tried to use other features of Modern C++ to fulfil tasks we’ve previously relied on the C preprocessor for. This article aims to cover all of these main features.

Continue reading “Replacing the Preprocessor in Modern C++”

Selecting Functions at Runtime

Not all choices can be made at compile-time, sometimes including which function (of several possibilities) to invoke. This article aims to cover all of the methods available to Modern C++ when selecting which function to call, with the decision made at runtime (based upon user input, for example). Terms covered in this article include function pointers, function objects, virtual functions and lambdas.

Continue reading “Selecting Functions at Runtime”

Signaling error conditions without exceptions

In this article we’re going to look at a feature new to C++23 which supports a way to return an error condition from a function where a result value was anticipated. This is enabled in a new header <expected> which (as far as I am aware) does not require specific compiler support. (MSVC 19.37 with /std:c++latest was used to test the program code in this article.)

Continue reading “Signaling error conditions without exceptions”

Selecting Functions at Compile Time

When writing C++, we like to do as much of the work as possible at compile time; with C++ being a statically-typed language, we know the type(s) involved when compilation is taking place. In this article we’ll look at how to pass and receive, variables and results, of differing types depending on the nature of the function call itself. The four methods we will examine are: function overloading, template specialization, tag dispatch, and SFINAE.

Continue reading “Selecting Functions at Compile Time”

Concepts 101

Concepts finally appeared in the language with the completion of C++20—I say finally as work to specify them had been going on continuously since before the release of C++11. This article attempts to explain their rationale and usage, with examples that should compile on any up-to-date C++ compiler when specifying -std=c++20 (or /std:c++20 for MSVC).

So why do we need concepts when template syntax has been available since C++98? Put simply, templates have been (successfully) used in ways that were never envisaged; however the reporting of invalid instantiations and similar errors has not kept pace. Also, the use of auto in function parameter lists gives us template syntax “invisibly”, which the novice/intermediate coder may not expect.

Continue reading “Concepts 101”

Designing Traits and Policy Classes

Traits and policy classes are often used with C++ generics, but their role and purpose is often something of an enigma even to experienced C++ programmers. The definitions of these two terms overlap to some extent, and could be summarized as follows:

  • Traits represent natural additional properties of a template parameter.
  • Policies represent configurable behavior for generic functions and types.

In this article the example code will show use of both of these two, with type information obtained through a (specialized) traits class and functionality obtained from a (generic) policy class.

Continue reading “Designing Traits and Policy Classes”

Applying Functional Programming Techniques to Modern C++

Functional programming (FP) is a discipline and practice of computer science where Mathematical concepts come to the fore. There are a number of popular FP languages out there, but we can stay with C++ and explore some of the themes of FP by using a subset of familiar syntax. In this article we’ll look at a number of FP concepts, such as purity, immutability and use of higher-order functions, and how they can be concisely and usefully represented in Modern C++.

1. Purity

A function is considered pure if its operation depends only upon its formal input parameters, that is not accessing any external (global) state. Global state in FP is a little like the historical Goto statement, shunned but sometimes necessary, and so is by design abstracted away as much as possible. A C++ lambda is pure if it has an empty capture clause, for example:

Continue reading “Applying Functional Programming Techniques to Modern C++”

Designing Classes for Serialization (4)

In the previous articles of this mini-series we’ve covered the use of custom serialization and deserialization functions to generate and interpret XML. In this article we’ll look at how to add to existing classes to give them the ability to utilize the (de-)serialization logic already written. The process is similar to before: create an in-memory model and then serialize it, or start with blank containers and then read in the data, checking for errors.

Continue reading “Designing Classes for Serialization (4)”

Designing Classes for Serialization (3)

In the previous articles we’ve looked at creating an in-memory XML hierarchy (or DOM), and serializing from and deserializing to this memory model. In this article we’re going to look at querying the DOM in a similar fashion to JavaScript methods such as document.getElementById() available in a browser. The scheme chosen is to overload operator [] (twice) and provide other convenience methods such as name() and numberOfChildren().

Continue reading “Designing Classes for Serialization (3)”

Designing Classes for Serialization (2)

The complement of serialization is deserialization, and this is typically more difficult as it requires character- or pattern-matching of the input, plus checking for erroneous input. To match a stream of XML the possibility of using std::getline() was considered, but this is too inflexible as regards whitespace. Stream input to a std::string was also considered, but again this is unsuitable as breaking all input at whitespace is not what is needed.

Continue reading “Designing Classes for Serialization (2)”

Designing Classes for Serialization (1)

Data held in memory must be saved to a store in order to outlive the running-time of the program it belongs to. Simply dumping binary data to disk is not usually the best way, or even a practicable way, of achieving this (think security issues, endianness, 32-bits/64-bits etc.)

The terms “serialization” and its companion “deserialization” are used to describe the conversion between the in-memory model and a (usually textual) disk-file representation. As an example, consider a web-browser which reads an HTML web page (and its dependencies) from a network connection and converts (deserializes) it into a format which can be manipulated through the DOM (Document Object Model). In this article we’ll concentrate more on serialization, which is often a simpler task.

Continue reading “Designing Classes for Serialization (1)”

Common mistakes to avoid in Modern C++ (1)

Learning a new programming language is hard, and is especially daunting when as a novice programmer the compiler rejects pretty much every program you write the first time you try to compile it. Of course, compiler errors and warnings are important as they encourage you to write correct code and ensure that your program actually runs at all, and works as expected.

C++ has traditionally been seen as one of the harder programming languages for beginners to pick up; ideally you should already have some coding experience under your belt in (an)other programming language(s) before trying to learn Modern C++. This mini-series intends to examine the parts of C++ that novice (and more experienced) programmers sometimes fail to understand fully, leading to buggy and/or sub-optimal code.

Continue reading “Common mistakes to avoid in Modern C++ (1)”