C++ - Reddit
226 subscribers
48 photos
8 videos
24.6K links
Stay up-to-date with everything C++!
Content directly fetched from the subreddit just for you.

Join our group for discussions : @programminginc

Powered by : @r_channels
Download Telegram
Is this a correct implementation of Rust's Result enum for Arduino's C++ environment?

Hello Reddit!

Previously, I tried to recreate Rust's `Result` enum in C++ for the ESP32.

https://old.reddit.com/r/cpp/comments/1aifn5o/recreating_the_rust_result_enum_in_c_on_an_esp32/

But I have since realized that my old version kinda sucked!

For context, Arduino doesn't support most of the C++ standard library, but the ESP32 does.

What I really wanted was something you could just paste into the Arduino IDE and it would just work.
Now that I've rewritten it, it's possible!


However, I'm kind of sad to admit that I used AI (Google Gemini) to code a lot of this. Specifically:

* the [`std::remove_reference`], [`std::move`], and [`std::declval`] alternatives

* the [`auto`] and [`declval`] type shenanigans on the [`Result::match`], [`Result::map`] methods to get them to support lambdas. My original version only supported function pointers (see the code in the link above)!

* the other overloads of [`expect`] (I understand that `&` is a reference and `&&` is an rvalue reference (which is a basically thing that can be [`move`]d from?), but I still don't have quite the deep knowledge on it to write all the proper overloads, especially with those being after the function signature?)

* the improved versions of the [`Result`] type's copy and move constructors and its assignment operators (I didn't know about placement new before trying to rewrite the [`Result`] type, and it completely slipped my mind that you had to call the destructor if the [`other`] in the assignment operator was of a different tag!)

Of course, I've read through the code that the AI wrote and it seems logically correct to me, and I've rewritten a lot of it so that it's in my own coding style.

But because I've written it with AI, I don't really trust it.

Could I ask for you guys' help?
I'm only a beginner-intermediate C++ coder,
so is there anything wrong with the code that I don't see?

Thanks in advance!

```

#ifndef RESULT_HPP
#define RESULT_HPP

#include <new>

template<typename P>
void println(P printable);

[[noreturn]] void never() noexcept {
while (true) {
}
}

template <typename M>
[[noreturn]] void panic(M message) noexcept {
println(message);
never();
}

template<typename T> struct remove_reference {
using type = T;
};
template<typename T> struct remove_reference<T &> {
using type = T;
};
template<typename T> struct remove_reference< T && > {
using type = T;
};

template<typename T>
constexpr typename remove_reference<T>::type &&move(T &&arg) noexcept {
return static_cast< typename remove_reference<T>::type && >(arg);
}

template<typename T>
typename remove_reference<T>::type &&declval() noexcept;

template<typename T, typename E>
class Result {
private:
struct OkOverload {
};
struct ErrOverload {
};

public:
static Result ok(const T &ok) {
return Result{
Tag::Ok,
ok,
OkOverload{}
};
}

static Result ok(T &&ok) {
return Result{
Tag::Ok,
move(ok),
OkOverload{}
};
}

static Result err(const E &error) {
return Result{
Tag::Err,
error,
ErrOverload{}
};
}

static Result err(E &&error) {
return Result{
Tag::Err,
move(error),
ErrOverload{}
};
}

template<typename OnOk, typename OnErr>
auto match(OnOk on_ok, OnErr on_err) && -> decltype(on_ok(declval<T>())) {
switch (_tag) {
case Tag::Ok:
return on_ok(move(_value.ok));
case Tag::Err:
return on_err(move(_value.error));
default:
panic("[_tag] was left in an invalid state!");
}
}

template<typename OnOk, typename OnErr>
auto match(OnOk on_ok, OnErr on_err) const & -> decltype(on_ok(declval<const T &>()))
Including a header that declares/defines the same symbols and names as a module after that module, should be an error class of its own.

I was initially planning to phrase this as a question, but this is something I've bumped up against repeatedly while iterating on `vulkan.cppm`, and was wondering what the wider community thinks of this, which is quite a common error to stumble upon when working with an intermediate codebase that has both module imports and headers.

The standard as far as I can tell doesn't explicitly say anything about this, but de-facto compiler behaviour (GCC, MSVC) is to allow headers-before-modules, but disallow the reverse ordering.

I'd like to know what everyone thinks about disallowing any #include statements after an import statement in the global module fragment (GMF)—effectively splitting it into two segments, which would also solve this problem.

https://redd.it/1oub82l
@r_cpp
vcpkg and include folders for opencv

Hello all,

I've recently encountered a weird bug on my end.

Basically, when I install the opencv package, vcpkg copies the built library in this folder

.\vcpkg_installed\x86-windows\x86-windows\include\opencv2.4

This means, when I try to include the files in my code I have to write them like this:

#include <opencv2.4/opencv2/opencv.hpp>

Now if I try to build you can already imagine what happens. I get a compiler error telling my that inside opencv.hpp the following include #include "opencv2/opencv_modules.hpp" couldn't be resolved.

It makes sense since the folders opencv2 and opencv should be placed directly under the include folder.

Has anyone experienced this? Does anyone know how I could fix it without moving the folders by hand?

Thanks in advance!

PS: I already tried with the package opencv and it's the same. It puts the library under .\vcpkg_installed\x86-windows\x86-windows\include\opencv4\opencv2


Edit: I guess I can just modify my project properties to include that additional include directory. But then my question is, shouldn't vcpkg take care of this exactly?

https://redd.it/1oud8ct
@r_cpp
Cursed arithmetic left shifts

So I recently came across a scenario where I needed to set a single bit in a 64 bit value. Simple:

uint64t result = 1ull << n;

I expected to rely on result being zero when n is out of range (n >= 64). Technically, this is how an arithmetic and logical shift would behave, according to their definitions as per wikipedia and technically intels x86 manual. Practically this is not how they behave on our hardware at all and I think this is interesting to share.

So I wrote this little test to see what happens when you shift out of range:

#include <iostream>
#include <bitset>
#include <stdint.h>

int main()
{
uint64
t bitpattern = 0xF0FF0FF00FF0FF0Full;
// shift overflow
for (uint64t shift = 0;shift <= 128ull;shift++)
{
uint64
t shiftresult = bitpattern << shift;
std::bitset<64> bitset
result(shiftresult);
std::cout << bitset
result << " for a shift of " << shift << std::endl;
}
return 0;
}

And right at the threshold to 64 the output does something funny:

1111000011111111000011111111000000001111111100001111111100001111 for a shift of 0
1110000111111110000111111110000000011111111000011111111000011110 for a shift of 1
1100001111111100001111111100000000111111110000111111110000111100 for a shift of 2
...
1110000000000000000000000000000000000000000000000000000000000000 for a shift of 61
1100000000000000000000000000000000000000000000000000000000000000 for a shift of 62
1000000000000000000000000000000000000000000000000000000000000000 for a shift of 63
1111000011111111000011111111000000001111111100001111111100001111 for a shift of 64
1110000111111110000111111110000000011111111000011111111000011110 for a shift of 65
1100001111111100001111111100000000111111110000111111110000111100 for a shift of 66

...
1100000000000000000000000000000000000000000000000000000000000000 for a shift of 126
1000000000000000000000000000000000000000000000000000000000000000 for a shift of 127
1111000011111111000011111111000000001111111100001111111100001111 for a shift of 128

It behaves as if result = input << n % 64; !!

So, I did a little bit of digging and found that GCC uses the SAL instruction (arithmetic shift) to implement this. From what I gathered, when working with unsigned types the logical shift should be used but this is of no relevance as SAL and SHL are apparently equivalent on x86_64 machines (which I can confirm).

What is far more interesting is that these instructions seem to just ignore out of range shift operands. I guess CPU's are wired to siply just care about the bottom 6 significant digits (or 5 in the case of the 32 bit wide instruction equivalent, as this also happens with 32 bit values at n = 32.) Notably, it does not happen at n = 16 for 16 bit values, they still use the 32 bit range.

MSVC and clang both do insert an SHL (logical left shift) instead of a SAL but the result is the same.

Now, there is one thing that really tripped me when debugging this initially:

uint64t result = 0;
uint64
t n = 63;
result = 1ull << (n + 1); // result is 1
result = 1ull << 64; // result is 0 !?

So, apparently, when GCC was able to just precompute the expression it would come up with the wrong result. This might be a compiler bug? This also happens on clang, I didn't test it on MSVC.



Just something I thought was interesting sharing. Took me quite a while to figure out what was happening and where my bug came from. It really stumped me for a day

https://redd.it/1ow3g9y
@r_cpp
Anyone else decided to ditch the baby with the bathwater and redesign C++ to fit their needs?

Really long story short, Ive had this idea in my head forever for a UEFI application, but I keep running into roadblocks actually trying to debug it whenever I try to implement it.

C is a little too old and really missing proper QOL features like templates, constructors, name scoping, etc.

Rust is great but I want to beat my face in with a rake dealing with memory allocations and the lifetime system

Zig is nearly perfect. not quite convinced on the build system yet but with better documentation, im sure ill be convinced. However, its impossible to output DWARF debug info for PE/COFF targets as is UEFI. Plus alot of the debugging features are broken in UEFI targets so actually finding bugs is near impossible.

So I got left with C++, after tasting the real freedom that is modern languages. Since UEFI is essentially a freestanding target anyway so I dont get stdlib support. So I figured fuck it, lets design a stdlib to fit my own needs.

#include <efi/typedef.h>
#include <efi/status.h>


#include <allocate.h>
#include <exit.h>


#include <QEMU/debugCon.h>


extern "C" Status efi_main(EFI_HANDLE ImageHandle, SystemTable* st, void* imageBase) {
Allocator iface = poolAllocator(st);


if (Option<Slice<char>> result = iface.alloc<char>(14); result.isSome()) {
Slice<char> str = result.unwrap();
const char* lit = "Hello World!\n";
for (uintmax_t i = 0; i < str.len; i++) {
str[i] = lit[i];
}


DebugCon::putChars(0, lit);
DebugCon::putChars(0, str.ptr);


iface.free(str);
}


return Status::Success;
}

After fighting with the compiler/linker for 2 weeks to get a bootable & debuggable image where UEFI, GDB, and the compiler wouldnt complain. I was finally able to write a CRT0 runtime, and modify the linker script for constructors/deconstructors. Then implement all the UEFI base types/definitions for a bare minimal environment and to properly handle debugging. Then I could start to implement core types like slice<t> and option<t> to handle things like memory allocations via a consumable interface.

Its been a rough several weeks, but im finally at the point where the "standard" library I will be using is starting to take enough shape. Just to make the above code run properly without bugs is \~2500 lines of code lol.

https://redd.it/1p7zlou
@r_cpp
what do you think about this

\#include <iostream>



\#define print(x) std::cout << x;



int main() {

char x[\] = " hello";

print("im dave," << x)



return 0;

}


can this be a problem?

https://redd.it/1p9owjg
@r_cpp
[Open Source] IACore: A battery-included C++20 foundation library (IPC, Async, HTTP, Logging) to escape dependency hell.

Hey friends,

Like many of you, I grew tired of "C++ Dependency Hell".. Every time I started a new project (specifically game engines and dev tools), I found myself wasting days setting up the same glue code: finding an HTTP library, setting up a job system, wrestling with platform-specific IPC, and configuring a logger.

I wanted a "bedrock" library—something I could drop into any project and immediately have the essentials working, without linking 50 different `.lib` files manually.

So I built **IACore**. It started as the internal core library for my work at **IASoft**, but I realized it solves a problem almost every C++ dev faces. I’ve cleaned it up, added tests, and I'm open-sourcing it under GPLv3 today.

**What's inside?** It wraps "best-in-class" dependencies into a unified, coherent C++20 API. It manages its own deps via CMake `FetchContent`, so you don't need to install anything manually.

* ** IPC:** High-performance shared-memory ring buffers (wait-free SPSC).
* **🧵 Async:** A work-stealing job scheduler (High/Normal priority queues).
* **🌐 Networking:** A clean wrapper around `cpp-httplib` that handles Zlib/Gzip compression automatically.
* **📂 IO:** Memory-mapped file operations and optimized binary stream readers/writers.
* **🛠️ Modern:** Uses `std::span`, `tl::expected`, and C++20 concepts throughout.

**Where to get it:** [https://github.com/I-A-S/IACore](https://github.com/I-A-S/IACore)

Any and all feedback & questions are welcome! (Even the rude ones—I know how r/cpp can be sometimes 😆 ).

# Examples

**1. Async Tasks**

C++

#include <IACore/AsyncOps.hpp>

// Initialize worker threads (hardware_concurrency - 2)
IACore::AsyncOps::InitializeScheduler();

// Schedule a task
auto* mySchedule = new IACore::AsyncOps::Schedule();

IACore::AsyncOps::ScheduleTask([](auto workerID) {
printf("Running on worker %d\n", workerID);
}, 0, mySchedule);

// Wait for completion
IACore::AsyncOps::WaitForScheduleCompletion(mySchedule);

**2. HTTP Request**

C++

#include <IACore/HttpClient.hpp>

IACore::HttpClient client("https://api.example.com");
auto res = client.JsonGet<MyResponseStruct>("/data", {});

if (res) {
std::cout << "Data: " << res->value << "\n";
} else {
std::cerr << "Error: " << res.error() << "\n";
}

**3. IPC (Shared Memory Ring Buffer)**

*Manager:*

C++

#include <IACore/IPC.hpp>

// Spawns a child process and connects via Shared Memory
auto nodeID = manager.SpawnNode("MyChildNodeExe");
manager.WaitTillNodeIsOnline(*nodeID);

// Send data with zero-copy overhead
String msg = "Hello Node";
manager.SendPacket(*nodeID, 100, {(PCUINT8)msg.data(), msg.size()});

*Node:*

C++

#include <IACore/IPC.hpp>

class Node : public IACore::IPC_Node {
public:
void OnSignal(uint8_t signal) override {
// Handle signals
}

void OnPacket(uint16_t packetID, std::span<const uint8_t> payload) override {
// Handle packets
}
};

int main(int argc, char* argv[]) {
// The connection string is passed as the first argument by the Manager
if (argc < 2) return -1;

Node node;
// Connect back to the manager via Shared Memory
if (!node.Connect(argv[1])) return -1;

while(true) {
node.Update();
}
return 0;
}

https://redd.it/1pni3y8
@r_cpp
Possible GCC reflection error

Playing with GCC I got a situation like this:

#include <algorithm>
#include <array>
#include <print>
#include <meta>


consteval auto Name(const int integer){
    return std::meta::displaystringof(^^integer);
}
consteval auto Name(const std::meta::info meta){
    return std::meta::displaystringof(meta);
}
// <source>:21:28: error: call to consteval function 'Name(^^int)' is not a constant expression
//    17 |     std::println("{}", Name(^^int));
//       |                        ~~~~^~~~~~~
// But removing const fix it!! (works in Clang P2996)




int main(){
    std::println("{}", Name(3));
    std::println("{}", Name(^^int));


    return 0;
}

I think that this is not the expected behaviour, but is it a known bug to be patched?

https://redd.it/1po9oz2
@r_cpp
Jubi - Lightweight 2D Physics Engine

Jubi is a passion project I've been creating for around the past month, which is meant to be a lightweight physics engine, targeted for 2D. As of this post, it's on v0.2.1, with world creation, per-body integration, built-in error detection, force-based physics, and other basic needs for a physics engine.

Jubi has been intended for C/C++ projects, with C99 & C++98 as the standards. I've been working on it by myself, since around late-November, early-December. It has started from a basic single-header library to just create worlds/bodies and do raw-collision checks manually, to as of the current version, being able to handle hundreds of bodies with little to no slow down, even without narrow/broadphase implemented yet. Due to Jubi currently using o(n²) to check objects, compilation time can stack fast if used for larger scaled projects, limiting the max bodies at the minute to 1028.

It's main goal is to be extremely easy, and lightweight to use. With tests done, translated as close as I could to 1:1 replicas in Box2D & Chipmunk2D, Jubi has performed the fastest, with the least amount of LOC and boilerplate required for the same tests. We hope, by Jubi-1.0.0, to be near the level of usage/fame as Box2D and/or Chipmunk2D.

Jubi Samples:

#define JUBIIMPLEMENTATION
#include "../Jubi.h"

#include <stdio.h>

int main() {
    JubiWorld2D WORLD = Jubi
CreateWorld2D();

// JBody2DCreateBox(JubiWorld2D *WORLD, Vector2 Position, Vector2 Size, BodyType2D Type, float Mass)
    Body2D *Box = JBody2D
CreateBox(&WORLD, (Vector2){0, 0}, (Vector2){1, 1}, BODYDYNAMIC, 1.0f);
   
    // ~1 second at 60 FPS
    for (int i=0; i < 60; i++) {
        Jubi
StepWorld2D(&WORLD, 0.033f);

        printf("Frame: %02d | Position: (%.3f, %.3f) | Velocity: (%.3f, %.3f) | Index: %d\n", i, Box -> Position.x, Box -> Position.y, Box -> Velocity.x, Box -> Velocity.y, Box -> Index);
    }
   
    return 0;
}

Jubi runtime compared to other physic engines:

|Physics Engine|Runtime|
|:-|:-|
|Jubi|0.0036ms|
|Box2D|0.0237ms|
|Chipmunk2D|0.0146ms|

Jubi Github: https://github.com/Avery-Personal/Jubi

https://redd.it/1prwf8o
@r_cpp
Semantics
Perfect Forwarding
Smart Pointers
constexpr
Initializer Lists
Delegating Constructors

C++14 FEATURES
Generic Lambdas
Return Type Deduction
Binary Literals
Variable Templates

C++17 FEATURES
Structured Bindings
if/switch with initializers
std::optional
std::variant
std::any
Fold Expressions
Inline Variables

C++20 FEATURES
Concepts
Ranges
Coroutines
Modules
Three-way Comparison (<=>)
std::span

MEMORY MANAGEMENT
Stack vs Heap
RAII (Resource Acquisition Is Initialization)
Smart Pointers
- unique_ptr
- shared_ptr
- weak_ptr
Custom Allocators
Memory Pools

EXCEPTION HANDLING
try-catch blocks
throw keyword
Exception Classes
Standard Exceptions
noexcept specifier
Exception Safety Guarantees

FILE I/O
Stream Classes
- ifstream, ofstream, fstream
File Operations
Binary File I/O
String Streams
Formatting

MULTITHREADING
std::thread
Mutexes and Locks
Condition Variables
Atomic Operations
Thread-local Storage
Futures and Promises
async

PREPROCESSOR
Macros
#include
Header Guards
#pragma once
Conditional Compilation

ADVANCED TOPICS
Type Casting
- static_cast
- dynamic_cast
- const_cast
- reinterpret_cast
RTTI (Runtime Type Information)
Operator Overloading
Copy Elision and RVO
Perfect Forwarding
Name Mangling
Linkage

COMPILATION AND BUILD
Compilation Process
Header Files
Source Files
Linking
Build Systems
- Make
- CMake
Compiler Options

Requested a AI to provide a CPP roadmap to know CPP very thoroughly, and it has provided me this roadmap. Do you have additions? Or is this good for modern CPP?

https://redd.it/1pug6hs
@r_cpp
Is modules thought to work seamlessly with external dependencies using #import

Let's say I want to convert my project to use modules instead of #includes. So I replace every #include <vector> with import <vector>?
What happens with all my external dependencies using #include <vector>?

Does this cause conflicts in some way, or does it work seamlessly?



https://redd.it/1q1ekad
@r_cpp
MayaFlux 0.1.0: A Digital-Native Substrate for Multimedia Computation

Hello r/cpp folks,

I am very excited to announce the initial release of my new creative multimedia programming framework. Here is a short release text, you can find the full context on the [website](https://mayaflux.org/releases/)

MayaFlux 0.1.0 is a C++20/23 infrastructure built to replace the 1980s-era architectures still underlying modern creative coding tools. Built with 15 years of interdisciplinary practice and DSP engineering, it departs from the "analog metaphors" that have constrained digital creativity since the 1980s. MayaFlux does not simulate oscillators or patch cables; it processes unified numerical streams through lock-free computation graphs.

## The Death of Analog Metaphor

Traditional tools (DAWs, visual patchers) rely on legacy pedagogical metaphors. MayaFlux rejects these in favor of computational logic. In this framework, **audio, visuals, and control data are identical.** Every sample, pixel, and parameter is a double-precision floating-point number. This eliminates the artificial boundaries between domains. A single unit can output audio, trigger GPU compute shaders, and coordinate temporal events in the same processing callback without conversion overhead.

## Technical Core: Lock-Free & Deterministic

Building on C++20, MayaFlux utilizes `atomic_ref` and compare-exchange operations to ensure thread safety without mutexes. You can restructure complex graphs or inject new nodes while audio plays -> no glitches, no dropouts, and no contentions. The state promise ensures every node processes exactly once per cycle, regardless of how many consumers it has, enabling true multi-rate adaptation (Audio, Visual, and Custom rates) within a unified graph.

## Lila: Live C++ via LLVM JIT

One of MayaFlux's most transformative features is the **Lila JIT system**. Utilizing LLVM 21+, Lila allows for full C++20 syntax evaluation (including templates and `constexpr`) in real-time. There is no "application restart" or "compilation wait." You write C++ code, hit evaluate, and hear/see the results within one buffer cycle. Live coding no longer requires switching to a "simpler" interpreted language; you have the full power of the C++ compiler in the hot path.

## Graphics as First-Class Computation

Unlike tools where graphics are a "visualization" afterthought, MayaFlux treats the **Vulkan 1.3** pipeline with the same architectural rigor as audio DSP. The graphics pipeline shares the same lock-free buffer coordination and node-network logic. Whether you are driving vertex displacement via a recursive audio filter or mapping particle turbulence to a high-precision phasor, the data flow is seamless and low-level.

## Temporal Materiality

By utilizing **C++20 Coroutines**, MayaFlux turns Time into a compositional material. Through the `co_await` keyword, developers can suspend logic on sample counts, frame boundaries, or predicates. This eliminates "callback hell" and allows temporal logic to be written exactly how it is imagined: linearly and deterministically.

## Who is it for?

MayaFlux is infrastructure, not an application. It is for:

- **Creative Technologists** hitting the limits of Processing or Max/MSP.
- **Researchers** needing direct buffer access and novel algorithm implementation.
- **Developers** seeking low-level GPU/Audio control without framework-imposed boundaries.

The substrate is ready. Visit **mayaflux.org** to start sculpting data.

## A quick teaser

```cpp
#pragma once
#define MAYASIMPLE
#include "MayaFlux/MayaFlux.hpp"

void settings() {
// Low-latency audio setup
auto& stream = MayaFlux::Config::get_global_stream_info();
stream.sample_rate = 48000;
}

void compose() {

// 1. Create the bell
auto bell = vega.ModalNetwork(
12,
220.0,
ModalNetwork::Spectrum::INHARMONIC)[0]
| Audio;

// 2. Create audio-driven logic
auto source_sine = vega.Sine(0.2, 1.0f); // 0.2 Hz slow oscillator

static double last_input = 0.0;
auto
MayaFlux 0.1.0: A Digital-Native Substrate for Multimedia Computation

Hello r/cpp folks,

I am very excited to announce the initial release of my new creative multimedia programming framework. Here is a short release text, you can find the full context on the [website](https://mayaflux.org/releases/) or the [git repo](https://github.com/MayaFlux/MayaFlux)

MayaFlux 0.1.0 is a C++20/23 infrastructure built to replace the 1980s-era architectures still underlying modern creative coding tools. Built with 15 years of interdisciplinary practice and DSP engineering, it departs from the "analog metaphors" that have constrained digital creativity since the 1980s. MayaFlux does not simulate oscillators or patch cables; it processes unified numerical streams through lock-free computation graphs.

# The Death of Analog Metaphor

Traditional tools (DAWs, visual patchers) rely on legacy pedagogical metaphors. MayaFlux rejects these in favor of computational logic. In this framework, **audio, visuals, and control data are identical.** Every sample, pixel, and parameter is a double-precision floating-point number. This eliminates the artificial boundaries between domains. A single unit can output audio, trigger GPU compute shaders, and coordinate temporal events in the same processing callback without conversion overhead.

# Technical Core: Lock-Free & Deterministic

Building on C++20, MayaFlux utilizes `atomic_ref` and compare-exchange operations to ensure thread safety without mutexes. You can restructure complex graphs or inject new nodes while audio plays -> no glitches, no dropouts, and no contentions. The state promise ensures every node processes exactly once per cycle, regardless of how many consumers it has, enabling true multi-rate adaptation (Audio, Visual, and Custom rates) within a unified graph.

# Lila: Live C++ via LLVM JIT

One of MayaFlux's most transformative features is the **Lila JIT system**. Utilizing LLVM 21+, Lila allows for full C++20 syntax evaluation (including templates and `constexpr`) in real-time. There is no "application restart" or "compilation wait." You write C++ code, hit evaluate, and hear/see the results within one buffer cycle. Live coding no longer requires switching to a "simpler" interpreted language; you have the full power of the C++ compiler in the hot path.

# Graphics as First-Class Computation

Unlike tools where graphics are a "visualization" afterthought, MayaFlux treats the **Vulkan 1.3** pipeline with the same architectural rigor as audio DSP. The graphics pipeline shares the same lock-free buffer coordination and node-network logic. Whether you are driving vertex displacement via a recursive audio filter or mapping particle turbulence to a high-precision phasor, the data flow is seamless and low-level.

# Temporal Materiality

By utilizing **C++20 Coroutines**, MayaFlux turns Time into a compositional material. Through the `co_await` keyword, developers can suspend logic on sample counts, frame boundaries, or predicates. This eliminates "callback hell" and allows temporal logic to be written exactly how it is imagined: linearly and deterministically.

# Who is it for?

MayaFlux is infrastructure, not an application. It is for:

* **Creative Technologists** hitting the limits of Processing or Max/MSP.
* **Researchers** needing direct buffer access and novel algorithm implementation.
* **Developers** seeking low-level GPU/Audio control without framework-imposed boundaries.

The substrate is ready. Visit **mayaflux.org** to start sculpting data.

# A quick teaser
```cpp
#pragma once
#define MAYASIMPLE
#include "MayaFlux/MayaFlux.hpp"

void settings() {
// Low-latency audio setup
auto& stream = MayaFlux::Config::get_global_stream_info();
stream.sample_rate = 48000;
}

void compose() {

// 1. Create the bell
auto bell = vega.ModalNetwork(
12,
220.0,
ModalNetwork::Spectrum::INHARMONIC)[0]
| Audio;

// 2. Create
No compiler implements std linalg

Tested in visual 2026 with std latest and several other compilers in godbolt with the appropriate c++2026 or latest options, no one accepts #include <linalg>. Did I miss something or no compiler does implement std linalg yet ? (Out of curiosity, as it's really not urgent, it's not like blas/lapack etc are not around since decades.)

https://redd.it/1q6myiw
@r_cpp
C++26 Reflection: Autocereal - Use the Cereal Serialization Library With Just A #include (No Class Instrumentation Required)

I ran this up to show and tell a couple days ago, but the proof of concept is much further along now. My goal for this project was to allow anyone to use Cereal to serialize their classes without having to write serialization functions for them. This project does that with the one exception that private members are not being returned by the reflection API (I'm pretty sure they should be,) so my private member test is currently failing. You will need to friend class cereal::access in order to serialize private members once that's working, as I do in the unit test.


Other than that, it's very non-intrusive. Just include the header and serialize stuff (See the Serialization Unit Test Nothing up my sleeve.


If you've looked at Cereal and didn't like it because you had to retype all your class member names, that will soon not be a concern. Writing libraries is going to be fun for the next few years!

https://redd.it/1qq2npd
@r_cpp
P1689's current status is blocking module adoption and implementation - how should this work?

There is a significant "clash of philosophies" regarding Header Units in the standard proposal for module dependency scanning P1689 (it's not standard yet because it doesn't belong to the language standard and the whole ecosystem is thrown to trash by now but it's de facto) that seems to be a major blocker for universal tooling support.

# The Problem

When scanning a file that uses header units, how should the dependency graph be constructed? Consider this scenario:

// a.hh
import "b.hh";

// b.hh
// (whatever)

// c.cc
import "a.hh";

When we scan c.cc, what should the scanner output?

Option 1: The "Module" Model (Opaque/Non-transitive) The scanner reports that c.cc requires a.hh. It stops there. The build system is then responsible for scanning a.hh separately to discover it needs b.hh.

Rationale: This treats a header unit exactly like a named module. It keeps the build DAG clean and follows the logic that `import` is an encapsulated dependency.

Option 2: The "Header" Model (Transitive/
Include-like) The scanner resolves the whole tree and reports that `c.cc` requires both `a.hh` and `b.hh`.

Rationale: Header units are still headers. They can export macros and preprocessor state. Importing a.hh is semantically similar to including it, so the scanner should resolve everything as early as possible (most likely using traditional -I paths), or the impact on the importing translation unit is not clear.

# Current Implementation Chaos

Right now, the "Big Three" are all over the place, making it impossible to write a universal build rule:

1. Clang (clang-scan-deps): Currently lacks support for header unit scanning.
2. GCC (-M -Mmodules): It essentially deadlocks. It aborts if the Compiled Module Interface (CMI) of the imported header unit isn't already there. But we are scanning specifically to find out what we need to build!
3. MSVC: Follows Option 2. It resolves and reports every level of header units using traditional include-style lookup and aborts if the physical header files cannot be found.

# The Two Core Questions

1. What is the scanning strategy? Should import "a.hh" be an opaque entry as it is in the DAG, or should the scanner be forced to look through it to find b.hh?

2. Looking-up-wise, is import "header" a fancy #include or a module?

If it's a fancy include: Compilers should use `-I` (include paths) to resolve them during the scan. Then we think of other ways to consume their CMIs during the compilation.
If it's a module: They should be found via module-mapping mechanics (like MSVC's /reference or GCC's module mapper).

# Why this matters

We can't have a universal dependency scanning format (P1689) if every compiler requires a different set of filesystem preconditions to successfully scan a file, or if each of them has their own philosophy for scanning things.

If you are a build system maintainer or a compiler dev, how do you see this being resolved? Should header units be forced into the "Module" mold for the sake of implementation clarity, or must we accept that they are "Legacy+" and require full textual resolution?

I'd love to hear some thoughts before this (hopefully) gets addressed in a future revision of the proposal.

https://redd.it/1qx7zex
@r_cpp
"override members" idea as a gateway to UFCS (language evolution)

(UFCS backgrounder: https://isocpp.org/files/papers/N4174.pdf )

I have two functions that tell me if a string contains the
characters of a particular integer. They're called hasInt and intIn.
(intIn is inspired by the python keyword in.)
They looks like this:

bool hasInt(const string s, int n)// does s have n?
{
return s.contains(tostring(n));
}

bool intIn(int n, const string s)// is n in s?
{
return s.contains(to
string(n));
}

It would be convenient if I could add hasInt as a member function to std::string:

bool string::hasInt(int n)
{
return ::hasInt(this, n);
}

Then I could use "member syntax" to call the function, like `text.hasInt(123)`.

Of course, that's not possible, because then I'd be changing the header files
in the standard libraries.

Here's an idea for a new language feature:
let's use the `override` keyword to allow us to "inject" member functions
into an existing class, without modifying the class definition. So the code:

override bool string::hasInt(int n)
{
return ::hasInt(
this, n);
}

will (in effect) add hasInt as a member function to string.

Thus, this "override member function" feature has a syntax like:

ReturnType ClassName::function(args){...etc...}

HOWEVER..... what if ClassName doesn't necessarily need to be a class, and could be
other types? Then you open the door to override members like:

override bool int::intIn(const string s)
{
return ::intIn(this, s);
}

Which allows code like `(123).intIn(text)`.

This is halfway to UFCS!

Using some macro magic and helper templates, we could define a
MAKE_UFCS macro to convert a non-member function into a member function:

#define MAKE_UFCS(f) \
override \
retType(f) argType1(f)::f(argType2(f) x)\
{ \
return f(
this, x); \
}

Thus the non-member functions hasInt and intIn could be "opted in" to UFCS
by the macro calls:

MAKEUFCS(hasInt);
MAKE
UFCS(intIn);

Or maybe, if this override-to-UFCS is useful enough, the override feature can be
applied to a collection of functions at once, like:

override hasInt, intIn;

or

override {
#include <cstdlib>
}

To UFCS-ify an entire header file at the same time.

EDIT: this idea would be similar to Scala's "Extension Methods": https://docs.scala-lang.org/scala3/book/ca-extension-methods.html

or C#'s "Extension Members": https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

https://redd.it/1qyikcg
@r_cpp
MigrationManager::GetInstance();
manager.CreateMigrationHistory();
size_t applied = manager.ApplyPendingMigrations();
```

Supports rollbacks, dry-run preview, checksum verification, and distributed locking for safe concurrent deployments.

---

## Backup & Restore

Full database backup/restore with progress reporting:

```cpp
#include <Lightweight/SqlBackup.hpp>

// Backup to compressed archive (multi-threaded)
SqlBackup::Backup(
"backup.zip",
connectionString,
4, // concurrent workers
progressManager,
"", // schema
"*", // table filter (glob)
{}, // retry settings
{ .method = CompressionMethod::Zstd, .level = 6 }
);

// Restore
SqlBackup::Restore("backup.zip", connectionString, 4, progressManager);
```

Preserves indexes, foreign keys (including composite), and supports table filtering.

---

## Supported Databases

- Microsoft SQL Server
- PostgreSQL
- SQLite3

Works anywhere ODBC works (Windows, Linux, macOS).

---

## What's Next

We're actively developing and would love feedback. The library is production-ready for our use cases, but we're always looking to improve the API and add features.

We also consider abstracting away ODBC such that it could support non-ODBC databases like SQLite3 directly without the ODBC layer. That's a longer-term goal, but definitely a goal.

We currently focus on SQL tooling (migrations and backup/restore) as both are quite young additions that are still evolving.

Questions and PRs welcome!

https://redd.it/1r0co80
@r_cpp
Corosio Beta - coroutine-native networking for C++20

We are releasing the Corosio beta - a coroutine-native networking library for C++20 built by the C++ Alliance. It is the successor to Boost.Asio, designed from the ground up for coroutines.

**What is it?**

Corosio provides TCP sockets, acceptors, TLS streams, timers, and DNS resolution. Every operation is an awaitable. You write co\_await and the library handles executor affinity, cancellation, and frame allocation. No callbacks. No futures. No sender/receiver.

It is built on Capy, a coroutine I/O foundation that ships with Corosio. Capy provides the task types, buffer sequences, stream concepts, and execution model. The two libraries have no dependencies outside the standard library.

**An echo server in 45 lines:**

#include <boost/capy.hpp>
#include <boost/corosio.hpp>

namespace corosio = boost::corosio;
namespace capy = boost::capy;

capy::task<> echo_session(corosio::tcp_socket sock)
{
char buf[1024];
for (;;)
{
auto [ec, n] = co_await sock.read_some(
capy::mutable_buffer(buf, sizeof(buf)));

auto [wec, wn] = co_await capy::write(
sock, capy::const_buffer(buf, n));

if (ec)
break;
if (wec)
break;
}
sock.close();
}

capy::task<> accept_loop(
corosio::tcp_acceptor& acc,
corosio::io_context& ioc)
{
for (;;)
{
corosio::tcp_socket peer(ioc);
auto [ec] = co_await acc.accept(peer);
if (ec)
continue;
capy::run_async(ioc.get_executor())(echo_session(std::move(peer)));
}
}

int main()
{
corosio::io_context ioc;
corosio::tcp_acceptor acc(ioc, corosio::endpoint(8080));
capy::run_async(ioc.get_executor())(accept_loop(acc, ioc));
ioc.run();
}

**Features:**

* Coroutine-only - every I/O operation is an awaitable, no callbacks
* TCP sockets, acceptors, TLS streams, timers, DNS resolution
* Cross-platform: Windows (IOCP), Linux (epoll), macOS/FreeBSD (kqueue)
* Type-erased streams - write any\_stream& and accept any stream type. Compile once, link anywhere. No template explosion.
* Zero steady-state heap allocations after warmup
* Automatic executor affinity - your coroutine always resumes on the right thread
* Automatic stop token propagation - cancel at the top, everything below stops Buffer sequences with byte-level manipulation (slice, front, consuming\_buffers, circular buffers)
* Concurrency primitives: strand, thread\_pool, async\_mutex, async\_event, when\_all, when\_any Forward-flow allocator control for coroutine frames
* C++20: GCC 12+, Clang 17+, MSVC 14.34+

**Get it:**

git clone https://github.com/cppalliance/corosio.git
cd corosio
cmake -S . -B build -G Ninja
cmake --build build

No dependencies. Capy is fetched automatically.

Or use CMake FetchContent in your project:

include(FetchContent)
FetchContent_Declare(corosio
GIT_REPOSITORY https://github.com/cppalliance/corosio.git
GIT_TAG develop
GIT_SHALLOW TRUE)
FetchContent_MakeAvailable(corosio)
target_link_libraries(my_app Boost::corosio)

**Links:**

* Corosio: [https://github.com/cppalliance/corosio](https://github.com/cppalliance/corosio)
* Corosio docs: [https://develop.corosio.cpp.al/](https://develop.corosio.cpp.al/)
* Capy: [https://github.com/cppalliance/capy](https://github.com/cppalliance/capy)
* Capy docs: [https://develop.capy.cpp.al/](https://develop.capy.cpp.al/)

**What’s next:**

HTTP, WebSocket, and high-level server libraries are in development on the same foundation. Corosio is heading for Boost formal review. We want your feedback.

https://redd.it/1rqykml
@r_cpp
Modern declarative EDSL for graphic user interface in C++? Not QML or XAML.

Hello everyone,

I have been investigating lately (after using NiceGUI for a real project) and learning Jetpack Compose (not writing any real code with it, would do it with Jetpack Multiplatform if ever).

I am really impressed by Jetpack Compose approach, especially UDF.

I thought there could possibly not be a better way than MVVM tbh, after using it for years.

But after seeing how declarative composition inside the language, not with XAML or QML can be done, I am sold in the amount of boilerplate that can be saved, plus the better integration when the dsl is in the host language.

So I wanted to mention I found this, which I think could be a good start for some experiments, on top of wxWidgets: https://github.com/rmpowell77/wxUI

I think it has a talk in CppCon2025 here: https://www.youtube.com/watch?v=xu4pI72zlO4

Kudos to the author for bringing something like this to C++! Definitely useful.

I would like to hear your opinions on this style of EDSL GUI embedding and pros/cons you find for those of you who do GUI programming all the time.

Also, wild idea: with the power of compile-time C++ programming and C++26 reflection, it would be possible to get existing xaml interfaces and convert it into regular C++ at compile-time via #embed or #include and not even changing the EDSL itself and making it directly embedded and reusable in C++? That would be plenty useful.


https://redd.it/1ry51fg
@r_cpp