Skip to content

Instantly share code, notes, and snippets.

View ckwastra's full-sized avatar

Vincent X ckwastra

View GitHub Profile

Corner cases in std::optional initialization

It has been one year since my previous post: Initialization in C++: A corner case. In this post, I would like to share some corner cases (with implementation divergences) encountered while testing std::optional's constructors. To maximize flexibility and usability, std::optional provides a rich set of overloaded constructors, along with some heavy SFINAE logic to disambiguate them.1 The downside is that certain forms of initialization may behave unexpectedly. In the following sections, I will present several examples and explain how they are interpreted by various implementations and by the C++ standard. All references to the standard are to N4950 (the C++23 final draft).

Introduction

First, let's write down the re

Footnotes

  1. This topic is discussed in detail in Barry's post: Getting in trouble with mixed construction.

Implement assert in CMake

Assertions are powerful tools for verifying function preconditions and postconditions, catching bugs early in development, and ultimately leading to more robust code. Many popular programming languages include built-in support for assertions. Unfortunately, CMake does not currently provide a built-in assert command. While it's arguable that CMake's if command can already cover much of this functionality, a dedicated assert command would be a valuable addition. It offers a more concise and expressive syntax, improving both readability and intent. This post explores several approaches to implementing assert in the CMake language and discusses why it would be best implemented as a built-in CMake command.

The goal

Our goal is to implement an assert command that can be used by other CMake code. This command should accept the same arguments as the existing if command. It should raise an error if the arguments are invalid or if the evaluated condition is false. In such

Initialization in C++: A corner case

Recently, I've been trying to find out the difference between copy-initialization (e.g. in return statements) and direct-initialization (e.g. in static_cast expressions). Besides the explicit keyword, the code posted by Johannes really caught my attention because recent versions of GCC and Clang exhibit different behaviors for the mentioned code. Upon further investigation, it may be surprising that these behaviors are somewhat intentional. In the following, I will try to explain this corner case of initialization in C++. This post may be a bit arcane. Anyway, have fun reading!

Introduction

Given the following code:

// -std=c++23