UPDATE: although the book is now available both on packtpub.com and Amazon.com, it still appears on Amazon that “This title will be released on August 4, 2017”. The reason for this is that it takes 2-12 days for reprocessing a title update on Amazon.

I am pleased to announce that my book on modern C++ programming has been published by PacktPub. The book is called Modern C++ Programming Cookbook and can be ordered at packtpub.com and Amazon. The complete table of contents is available below.

The front cover

The book is organized in recipes, much like a cookbook (therefore the name). These recipes are organized in sections that introduce you to the topic, list any necessary pre-requisites and then explain how to do something and how that works. Throughout 112 recipes, the book covers both language and library features from C++11, C++14 and C++17, including the libraries for strings, containers, algorithms, iterators, input/output, regular expressions, threads, filesystem, atomic operations, and utilities. Besides that, there is a chapter for patterns and idioms and one dedicated for testing frameworks, that covers everything you need to know to get started with Boost.Test, Google Test and Catch.

This book is intended for all C++ developers, regardless of their experience. The beginner and intermediate developers will benefit the most from the book in their attempt to become prolific with C++. Experienced C++ developers, on the other hand, will find a good reference for many C++11, C++14, and C++17 language and library features that may come in handy from time to time. However, the book requires prior basic knowledge of C++, such as functions, classes, templates, namespaces, macros, and others. If you are not familiar with C++ at all, you should first read an introductory book to familiarize yourself with the core aspects.

Although C++17 has not yet been ratified as an ISO standard, the final version that is up for the ballot is well defined. In my book I discuss most of the important language and library features that made it into C++17. The C++17 features discussed in the book are:

  • structured bindings
  • fold expressions
  • constexpr if
  • new attributes ([[fallthrough]], [[nodiscard]], [[maybe_unused]])
  • new type deduction rules for list initialization
  • range based for loops improvements
  • general form of lambda expressions
  • std::invoke() and std::apply()
  • static_assert changes
  • non-member container access functions std::data(), std::size(), and std::empty()
  • std::search() searchers (Boyer-Moore and Boyer-Moore-Horspool)
  • chrono changes (floor(), round(), ceil(), and abs())
  • std::any
  • std::optional
  • std::variant (2 recipes)
  • std::string_view
  • std::scoped_lock
  • filesystem library (5 recipes)
  • shared_ptr and unique_ptr changes

All the samples in the book have been tested with VC++ 2017 (where possible), GCC 7 and Clang 5. All the language and library features discussed in the book are available with these versions of the mentioned compilers, except for a few exceptions for VC++. At this time, the following features are still not supported in VC++:

  • structured bindings
  • fold expressions
  • constexpr if
  • searchers for std::search()

If you do not have the latest versions of these compilers, you can try all the samples in the book with an online compiler. gcc and Clang are available at wandbox.org and VC++ is available at webcompiler.cloudapp.net.

Table of contents

  1. Learning Modern Core Language Features
    • Using auto whenever possible
    • Creating type aliases and alias templates
    • Understanding uniform initialization
    • Understanding the various forms of non-static member initialization
    • Controlling and querying object alignment
    • Using scoped enumerations
    • Using override and final for virtual methods
    • Using range-based for loops to iterate on a range
    • Enabling range-based for loops for custom types
    • Using explicit constructors and conversion operators to avoid implicit conversion
    • Using unnamed namespaces instead of static globals
    • Using inline namespaces for symbol versioning
    • Using structured bindings to handle multi-return values
  2. Working with Numbers and Strings
    • Converting between numeric and string types
    • Limits and other properties of numeric types
    • Generating pseudo-random numbers
    • Initializing all bits of internal state of a pseudo-random number generator
    • Using raw string literals to avoid escaping characters
    • Creating cooked user-defined literals
    • Creating raw user-defined literals
    • Creating a library of string helpers
    • Verifying the format of a string using regular expressions
    • Parsing the content of a string using regular expressions
    • Replacing the content of a string using regular expressions
    • Using string_view instead of constant string references
  3. Exploring Functions
    • Defaulted and deleted functions
    • Using lambdas with standard algorithms
    • Using generic lambdas
    • Writing a recursive lambda
    • Writing a function template with a variable number of arguments
    • Using fold expressions to simplify variadic function templates
    • Implementing higher-order functions map and fold
    • Composing functions into a higher-order function
    • Uniformly invoking anything callable
  4. Preprocessor and Compilation
    • Conditionally compiling your source code
    • Using the indirection pattern for preprocessor stringification and concatenation
    • Performing compile-time assertion checks with static_assert
    • Conditionally compiling classes and functions with enable_if
    • Selecting branches at compile time with constexpr if
    • Providing metadata to the compiler with attributes
  5. Standard Library Containers, Algorithms, and Iterators
    • Using vector as a default container
    • Using bitset for fixed-size sequences of bits
    • Using vector for variable-size sequences of bits
    • Finding elements in a range
    • Sorting a range
    • Initializing a range
    • Using set operations on a range
    • Using iterators to insert new elements in a container
    • Writing your own random access iterator
    • Container access with non-member functions
  6. General Purpose Utilities
    • Expressing time intervals with chrono::duration
    • Measuring function execution time with a standard clock
    • Generating hash values for custom types
    • Using std::any to store any value
    • Using std::optional to store optional values
    • Using std::variant as a type-safe union
    • Visiting a std::variant
    • Registering a function to be called when a program exits normally
    • Using type traits to query properties of types
    • Writing your own type traits
    • Using std::conditional to choose between types
  7. Working with Files and Streams
    • Reading and writing raw data from/to binary files
    • Reading and writing objects from/to binary files
    • Using localized settings for streams
    • Using I/O manipulators to control the output of a stream
    • Using monetary I/O manipulators
    • Using time I/O manipulators
    • Working with filesystem paths
    • Creating, copying, and deleting files and directories
    • Removing content from a file
    • Checking the properties of an existing file or directory
    • Enumerating the content of a directory
    • Finding a file
  8. Leveraging Threading and Concurrency
    • Working with threads
    • Handling exceptions from thread functions
    • Synchronizing access to shared data with mutexes and locks
    • Avoiding using recursive mutexes
    • Sending notifications between threads
    • Using promises and futures to return values from threads
    • Executing functions asynchronously
    • Using atomic types
    • Implementing parallel map and fold with threads
    • Implementing parallel map and fold with tasks
  9. Robustness and Performance
    • Using exceptions for error handling
    • Using noexcept for functions that do not throw
    • Ensuring constant correctness for a program
    • Creating compile-time constant expressions
    • Performing correct type casts
    • Using unique_ptr to uniquely own a memory resource
    • Using shared_ptr to share a memory resource
    • Implementing move semantics
  10. Implementing Patterns and Idioms
    • Avoiding repetitive if…else statements in factory patterns
    • Implementing the pimpl idiom
    • Implementing the named parameter idiom
    • Separating interfaces from implementations with the non-virtual interface idiom
    • Handling friendship with the attorney-client idiom
    • Static polymorphism with the curiously recurring template pattern
    • Implementing a thread-safe singleton
  11. Exploring Testing Frameworks
    • Getting started with Boost.Test
    • Writing and invoking tests with Boost.Test
    • Asserting with Boost.Test
    • Using test fixtures with Boost.Test
    • Controlling output with Boost.Test
    • Getting started with Google Test
    • Writing and invoking tests with Google Test
    • Asserting with Google Test
    • Using test fixtures with Google Test
    • Controlling output with Google Test
    • Getting started with Catch
    • Writing and invoking tests with Catch
    • Asserting with Catch
    • Controlling output with Catch

Credits

It took about eight months to complete this book and I got a lot of help from several people that I would like to thank to. First of all, is the team at PacktPub; although there were more people involve that I actually am aware of, I would like to thank Anurag Ghogre, Subhalaxmi Nadar and Nitin Dasan for all the help they provided throughout this time and the work they put in the project, as well as the other people that were involved with this book. I also want to thank David Corbin, whom I know for many years as “The CPU Wizard”, for reviewing the book and providing valuable feedback that made the book better. And last, but not least, I want to thank my wife for putting up with me through the many days and nights that I worked on this project.

, , , , , , , , Hits for this post: 1527 .

Last week I was in Redmond for the Microsoft MVP 2016 Summit. At the same time, the ISO C++ committee was having its fall meeting in Issaquah, which is very close to Redmond. Therefore, after the summit ended, a group of VC++ MVPs, including myself, decided to make the short trip to Issaquah and attend as observers the meetings, that are actually opened for the public. It was a very interesting experience and I am glad that I had the opportunity to take it.

The committee is organized in several working groups (WG) and study groups (SG). You can actually read all about that here. These groups have separate meetings as they are focussed on different things. I have attended a meeting of the Evolution Working Group (aka EWG), as, at that point, it looked like the most interesting of them all. These meetings actually took place in the same location where the final version of C++14 was voted.

Apart from the topics that have been discussed, which I will not elaborate on here, even though they were interesting and important, it was rather the way the committee is working that it was of most interest to me. I always had the impression that discussions were held in the fashion of the debates in the British Parliament or something similar, and I was surprised to see a much more organized, though still vocal, group. People are patiently taking turns to speak, constantly come with unexpected arguments or counter examples and eventually take polls to see what is the group’s overall opinion on the discussed topic(s). It also helped understand the process proposals go through from an initial form to the one that is eventually voted, if that is the case. I realized that it is way too easy for us to complain that things take too much time to be accepted. The reality is there are so many details that have to be taken into account and it takes many people to see them all. Everything needs to be backward compatible and it takes a lot of scrutiny and proposal iterations to reach a generally accepted form.

Overall, it was definitely a trip worth making, and I am looking forward to doing that again. I also encourage all of you that are interested in that and have the opportunity to take it.

For information about the progress in Issaquah see Herb Sutter’s Trip report: Fall ISO C++ standards meeting (Issaquah).

, , , , Hits for this post: 5569 .

C++11 added a date and time utility library called chrono, available in namespace std::chrono and header <chrono>. The problem with it is that the library is a general purpose one and therefore lacks many useful features, such as working with dates, weeks, calendars, timezones and other related features. Fortunately, a rich date and time library based on chrono has been created by Howard Hinnant and is available on github. The library is called date and is actually a collection of several small libraries:

  • date: the main library, available in header date.h, defines new date and time classes and operations with them. All the other libraries are based on this one.
  • timezones: a library for timezones, available in files tz.h/tz.cpp, based on the IANA timezone database
  • chrono_io: a library for streaming durations, available in header chrono_io.h
  • iso_week: a library that implements the ISO week calendar, available in header iso_week.h
  • julian and islamic: libraries that implement the Julian and Islamic calendars, available in headers julian.h and islamic.h

You can find all the necessary documentation on github. Here are several links:

In this article we will look at some examples for working with dates and ISO weeks. This library introduces many new types to handle various date and time representations. Among these we will look at:

  • sys_days: A count of days since std::system_clock‘s epoch. This is a time_point with a resolution of a day, and is implicitly convertible to std::system_clock::time_point, that has a much smaller resolution (millisecond or nanosecond), but not the other way around. To go the other way you must use floor().
  • year_month_day: A type that holds a day with fields for year, month (1 to 12) and day (1 to 31).
  • year_month_weekday: A type that holds a day with fields for year, month (1 to 12), a day of the week (0 to 6), and an index in the range [1, 5] that indicates the number of the week in the month.
  • year_weeknum_weekday: A type that hold a year, a weeknum (1 to 53) and a weekday (0 to 6). This can convert implicitly to and from a sys_days.

For using the library we need the following:

  • include header date.h and namespaces date and date::literals
  • for iso weeks we also need header iso_week.h and namespaces iso_week and iso_week::literals
  • NOTICE: The namespaces date::literals and iso_week::literals define types and literal operators with the same name and therefore can lead to name collisions; therefore you should only include them in the scope where you need them.

We will use the following lambda expression to print various dates to the console:

NOTICE: All the ‘today’ and related dates below are based on 2016-10-31.

Let us look at some examples:

  • create sys_days objects (including literals):

  • create year_month_day objects (including literals):

  • creating year_month_weekday literals and converting to year_month_day

  • create year_month_day values for today, yesterday and tomorrow

  • create year_month_day values for first and last day of the month

    Update: The following, as indicated by Howard Hinnant in the comments, can also be used:

  • create iso_week literals

  • get the iso week number for today

We will look at more utilities and examples in another post.

, , , , , , Hits for this post: 6959 .

C++17 was supposed to be a major update of the C++ ISO standard. After the Jacksonville meeting (29.02 – 05.03) it looks like it’s rather going to be a major disappointment. I’m not trying to downplay the things that have been voted into the C++17 standard so far, but all major features we hoped for this new version were moved out: modules, concepts, ranges, coroutines, uniform function call syntax.

Here is a brief report of the meetings, Trip report: C++ meeting at Jacksonville, and a quote of what was moved out for the next version:

Let me start enumerating the things we are not going to have in C++17:

  • Modules: They will not be in C++17, but in a separate technical specification. That is really a pity, as we will be for more years without having what I was expecting to let me get rid of the text substitution paradigm of the include directive as well as improve compilation times.
  • Concepts: They will not be integrated in C++17, but stay for now in their own technical specification. There were concerns about some issues in the TS, which I do not consider essential. Despite that there is implementation experience and even other TS depends on it, it was rejected to move concepts to the IS.
  • Ranges: This is a library solution highly depending on concepts. So, no way.
  • Coroutines: There was a very sound proposal with implementation experience. However, again this was targeted to another technical specification.

Besides that, we also will not have the half of uniform function call syntax that I thought was not controversial. To be clear, I really wanted both halves.

You can discuss on the report on reddit. The general feeling is disappointment though.

On a side note, standard C++ library in Visual Studio 2015 update 2 is C++17 feature complete (on what has been voted so far prior to the Jacksonville meeting).

, , , , , , Hits for this post: 11806 .

The Oxford meeting of the ISO C++ standards committee between 15-20 April resulted in new features beeing into the draft paper of the C++0x standard.

One of the features refer to Unicode support: a new header, called <cuchar>, was introduced. This header makes available new built-in types char16_t and char32_t, as well as new prefixes u and U to designate UTF-16 and UTF-32 encoded characters and strings.

A list of all papers submited before the Oxford meeting can be found here.

More about the results of the Oxford meeting can be found in:

, , , Hits for this post: 18840 .