Skip to content

dbjwhs/cpp-snippets

Repository files navigation

C++ Code Snippets

A collection of self-contained C++ code snippets, examples, and mini-projects. Each snippet is independently buildable and includes its own CMake configuration.

Highlights

These are the pieces worth reading first — they demonstrate depth beyond tutorial-level C++:

Snippet Lines What It Demonstrates
concurrency/happens-before/ ~1,845 C++ memory model deep-dive with stress tests across all 6 memory orderings
concurrency/proactor/ ~3,705 POSA2 async I/O pattern — complete proactor implementation
cpp-features/cpp20/coroutines/ ~1,354 Complete generator with promise_type, co_await, co_yield
cpp-features/cpp23/turing-machines/ ~5,613 5 Turing machines culminating in a Universal TM
algorithms/bloom-filter/ ~1,149 Production-quality Bloom filter with VMware VADP context
algorithms/hyperloglog/ ~1,186 Cardinality estimation based on Flajolet et al.
concurrency/atomic/ ~1,000+ All memory orderings with lock-free producer-consumer
cpp-idioms/rule-of-five/ ~800+ Railway-oriented programming with C++23 std::expected
cpp-features/cpp23/expected/ ~600+ Modern error handling patterns
design-patterns/ 23+ patterns Complete GoF coverage plus C++-specific patterns (CRTP, etc.)

Building the Snippets

Each snippet is contained in its own directory with a CMakeLists.txt file. To build a specific snippet:

cd <snippet-directory>
mkdir build && cd build
cmake ..
make

Or you can elect to build everything at once.

  1. build_all.sh that:

    • Automatically finds and builds all CMake projects in your directory structure
    • Creates build directories as needed
    • Provides colored output and detailed logging
    • Shows a comprehensive summary of successful and failed builds with executable paths
    • --dry-run | -d argument to perform a dry run
    • --run | -r argument to perform run executable after build
  2. clean_all.sh that:

    • Finds and removes all build directories
    • Provides similar colored output and logging
    • Shows a summary of cleaned projects
    • --dry-run | -d argument to perform a dry run

Prerequisites

  • CMake 3.30 or higher
  • C++20 compliant compiler (see gotcha's below for linux)
  • Git

Snippets Index

Algorithms

Concurrency

Data Structures

Design Patterns

Creational

Structural

Behavioral

C++-Specific

  • crtp/ — Static polymorphism, mixin classes, object counting, compile-time interface enforcement

C++ Features

C++20 Features

C++23 Features

Core Language Features

C++ Idioms

Programming Techniques

Networking

Programming Paradigms

System Programming

Utilities

Examples

Contributing

Feel free to suggest improvements or report issues. Each snippet should:

  1. Be self-contained in its own directory
  2. Include a CMakeLists.txt file
  3. Have a README.md explaining its purpose and usage
  4. Include comments explaining complex logic
  5. Follow the repository's coding style

Snippet Directory Structure

Each snippet directory should follow this structure:

snippet-name/
├── CMakeLists.txt          # Build configuration
├── README.md               # Usage and explanation
├── include/                # Header files
│   └── snippet.hpp
└── src/                    # Source files
    └── snippet.cpp

Gotchas and errata

I am currently evaluating JetBrain's CLion which creates a directory in each project file called cmake-build-debug which if removed becomes a PITA.

Recreating the cmake-build-debug Directory

If you accidentally removed the cmake-build-debug directory, you can easily recreate it by following these steps:

1. Regenerate the Build Directory

Navigate to the root directory of your CMake project in your terminal or command prompt, then run:

cmake -DCMAKE_BUILD_TYPE=Debug ..

Note: Replace .. with the path to your CMakeLists.txt file if it's not in the same directory.

This command will reconfigure your project and generate the cmake-build-debug directory along with the necessary build files.

2. Rebuild Your Project

You can either:

  • Rebuild your project from within your IDE (Visual Studio or CLion)

OR

  • Use the following command from your terminal:
cmake --build . --target all

This will rebuild all the targets in your project.

Linux

As of this writing 2/17/2025 most of the projects are building on linux, see below for my setup instructions. However there still are six (6) project not building, I am working through issues on them currently.

C++20 std::format Build Issues and Resolution

Problem Description

Build failures occurred when attempting to use std::format in C++20 code. While the code built successfully in CLion, it failed during command line cmake/make builds with the error:

fatal error: format: No such file or directory

The system was initially running GCC 12.3.0 which had incomplete C++20 library support.

Root Cause

GCC 12 implementations shipped with partial C++20 support. Specifically, the std::format header was not included in the standard library headers, which explained why the <format> header could not be found during compilation.

Solution

The issue was resolved by upgrading to GCC 13, which provides complete C++20 support including the std::format implementation.

Step 1: Add Required Repository

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt update

Step 2: Install GCC 13

sudo apt install gcc-13 g++-13 libstdc++-13-dev

Step 3: Set System Defaults

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 130
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-13 130

Result

  • Successfully upgraded to GCC 13.1.0 (Ubuntu 13.1.0-8ubuntu1~22.04)
  • Full C++20 support including std::format
  • Code now builds correctly both in CLion and command line environments

Key Learning (saving you three hours of headaches)

When implementing C++20 features, particularly std::format, GCC 13 or later is required xfor complete standard library support. Earlier versions may have incomplete implementations of the C++20 standard library features.

License

This project is licensed under the MIT License - see the LICENSE file for details.


Note: This repository is actively maintained and growing. Check back regularly for new snippets and updates!

About

Advanced C++ patterns: memory model, coroutines, design patterns, probabilistic data structures

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors