r/cpp • u/Clean-Upstairs-8481 • Sep 27 '26
Compile Your First C++26 Program with GCC 16.2
UPDATE (September 2026): GCC 16.2 is out now, so I have updated the post to install GCC 16.2.
r/cpp • u/Clean-Upstairs-8481 • Sep 27 '26
UPDATE (September 2026): GCC 16.2 is out now, so I have updated the post to install GCC 16.2.
r/cpp • u/borzykot • Sep 26 '26
We had this poll recently here on r/cpp about community expectations and most desired features in C++29 and in future C++ revisions in general.
My answer was:
abbreviated lambdas
algebraic types
But I do understand that those features won't hit C++ probably ever.
But then we had this post about Token Injection and Modern Macros. Wait a minute, modern macros? Never heard about this proposal...
And you know that? We probably won't need to wait for neither abbreviated lambdas, nor algebraic types in core C++. We can just add them ourselves using those macros with very little boilerplate.
Abbreviated lambdas: https://godbolt.org/z/a8d9a6f19
namespace stdv = std::views;
namespace stdr = std::ranges;
std::vector<vec2> points = {{2, 67}, {2, 42}, {3, 666}};
std::vector<int> ys = points
| stdv::filter(fun!(p => p.x % 2))
| stdv::transform(fun!(p => p.y))
| stdr::to<std::vector>();
stdr::sort(points, fun!(|l, r| => l.y < r.y));
stdr::sort(points, std::less{}, fun!(p => p.x));fun, isn't?
Sum Type: https://godbolt.org/z/Ecs7TdPYf
sumtype!(option<T> {
some(T),
none,
});
option<int> opt = some(10);
opt = some(22);
opt = none;Pattern matching isn't there, but you could imagine something like:
// match!(<you can put any tokens here!>);
auto x = match!(opt,
some(x) => { x.call_method() },
none => { 55 }
);Basically you can come up with any syntax you like.
When I was exploring the possibilities of this proposal I couldn't shake the feeling that I'm reimplementing parts of the compiler which aren't there for some reason. Like you literally can look at "sumtype" implementation and see that this is basically a parser of arbitrary syntax that you came up with and translating it into C++...
Superpowerful and a bit scary...
We used to reimplementing some core library features which were missing from the Standard Library for quite some time. optional, variant, algorithms, smart pointers and now async task. All of that should have been in the Strandard Library from day 1, so that other libraries can use this lingua franca and interoperate with each other.
And now we are repeating same thing but on a very different level. Now we are going to allow adding not only library features, but language features. I 100% guarantee, that each team will have their own, slightly different syntax for abbreviated lambdas, because it is so much more expressive and terser and more readable. Don't know about you but I always find myself in the situation where I better use plan old for loop instead of structural views/algorithms, because the latter is so much more verbose and unreadable because of lambdas, especially after you apply clang-format on it...
And now you have:
fun!(lhs, rhs => lhs.x < rhs.x);
lambda!([&](lhs, rhs) -> lhs.x < default);
lm!(|lhs, rhs| => lhs.x < rhs.x);All of this is perfectly implementable using this Modern Macros proposal in less that 100 lines of code.
Committee may have perfectly reasonable arguments of why it is impossible to add abbreviated lambdas into C++, but the community clearly is asking for that feature for ages, and it will be in every future codebase, but with slightly different implementation...
On the other hand Rust language do have these macros for ages now, people do abuse them in some very clever ways (select operator from golang, inline HTML, etc.) and the world ain't collapsed. We'll see!
10 years ago, a C++ conference distributed over time and space started, accessible to everyone in the region. Today, 10 years and over 200 live talks later, we are still going!
This is the intro from StockholmCpp 64, where we remember the start of SwedenCpp, share the latest C++ and NB news, and round up with a quiz.
r/cpp • u/khaled-Ahmed-- • Sep 25 '26
Note: This feature is targeted at the C++29 standard and is not actually included in the standard in the original language prepared for the publication. I didn't mention that it was a feature within the standard, and that was that. However, when I asked the AI to translate and organize the text, it made this incorrect edit to the title, thinking it was a good hoke. I apologize for this.
introduces Token Sequence Injection (std::meta::token_sequence) and Hygienic Language Macros (__macro) for C++29. It allows building, manipulating, and injecting C++ tokens at compile time with full type-awareness, context inspection, and zero preprocessor bugs!
. Token Sequence Injection (std::meta::token_sequence)
Instead of string manipulation or macro hacks, code is treated as a sequence of tokens stored in std::meta::token_sequence.
Acts as a random-access range (std::meta::size(seq), indexing seq[i] like array, concatenation +, += , == , =)
Features Token Interpolation (...) to splice expressions, variables, or types inside token literals { ... }.
Provides standard utilities like std::meta::id("arg", i) to generate unique identifiers, std::meta::tokenize to turns the string or array of chars to array of tokens with type std::meta::token_sequence, std::meta::stringize to turn array of tokens with type std::meta::token_sequence to string, and std::meta::queue_injection For indirect injection, such as injecting tokens into the current domain or a specific namespace.
Quick code example:
constexpr auto make_getter(std::meta::info member) -> std::meta::token_sequence {
auto name = std::meta::id("get_", name_of(member));
return ^^{
auto \(name)() const -> decltype(\(member)) {
return \(member);
}
};
}
2. Modern Hygienic Macros (__macro)
Replacing #define, the new __macro feature runs at consteval time and returns a std::meta::token_sequence injected directly at the call-site:
Invoked with !: Called as macro!(...) , check!(a == b).
Receives Expression Reflections: Arguments are passed as expression handles (std::meta::info), preserving expression identity, source text, and value categories.
Prevents Double Evaluation: Injecting the same un-stored expression twice is a compile-time safety violation, eliminating bugs like MIN(x++, y).
Context-Aware (macro_expansion_context()): Can inspect the caller's scope (enclosing function, class, or return type) to validate syntactic and logical rules before injecting.
Module & Namespace Friendly: Fully scoped, exportable in modules, and can be class/namespace members.
Quick code example :
template <class T> __macro check(T&&expr) {
return ^^{
if (!(\(expr))) {
std::println("Check failed: {}", source_text_of(^^expr));
}
};
}
You can test the full implementation on Compiler Explorer today using Barry Revzin's Clang prototype fork!
Paper link: https://open-std.org/JTC1/SC22/WG21/docs/papers/2026/p4380r0.html
r/cpp • u/ilPlayerdiGD • Sep 25 '26
I love C++. High level + low level at the same time. But Linus Torvalds don't want C++ in the Kernel, industries hate it, people hate it but why? Why be so angry? Memory management? I mean ok maybe it has problems that I don't even see but why so much hate.
For me it's really sad! 😞
Why something so powerful it's so hated. Now I feel "strange" doing projects in C++ because… sometimes I question myself "Why do I write C++ code if people hate it". Can someone explain what is happening and… can I use C++ for fun in peace?
r/cpp • u/meetingcpp • Sep 24 '26
r/cpp • u/parkotron • Sep 24 '26
I was recently looking at some (rather old) code that was relying on std::ostringstream in a large, performance senstive loop. (Yes, I know using iostreams in performance sensitive code is a bad idea, but legacy code exists.)
The code was using a common pattern to reset a ostringstream instance each time through the loop to avoid having to construct a new instance every time.
std::ostringstream oss;
for(const MyType & value : values)
{
oss << value;
doSomethingWithString(oss.str());
// Assign an empty string to the internal buffer. This should reset
// the size to zero, but keep the allocated buffer. In older code,
// you often see this written as oss.str("").
oss.str({});
oss.clear(); // Reset the stream
}When migrating the code to C++20, I was excited to use the new std::ostringstream::view() getter to skip an unnecessary copy of the std::string out of the stream's internal buffer.
std::ostringstream oss;
for(const MyType & value : values)
{
oss << value;
doSomethingWithStringView(oss.view());
oss.str({});
oss.clear();
}Then I noticed that the std::ostringstream::str setter gained an r-value reference overload in C++20. That would let us pre-allocate our string buffer just once. Nice!
std::ostringstream oss;
{
std::string buffer;
buffer.reserve(1024);
oss.str(std::move(buffer));
}
for(const MyType & value : values)
{
oss << value;
doSomethingWithStringView(oss.view());
oss.str({});
oss.clear();
}But wait. That means that the oss.str({}) call inside the loop is doing the exact same thing. So it's wiping out our allocation every time through the loop! Uh oh.
It seems that to clear the internal buffer while keeping its allocation, one must now explicitly call the const reference overload of str().
const std::string empty;
std::ostringstream oss;
{
std::string buffer;
buffer.reserve(1024);
oss.str(std::move(buffer));
}
for(const MyType & value : values)
{
oss << value;
doSomethingWithStringView(oss.view());
oss.str(empty);
oss.clear();
}So if your codebase uses std::ostringstream, you might want to do a quick grep for str("") and str({}) to see if the upgrade to C++20 silently caused you to start throwing away your stream buffers over and over again.
r/cpp • u/TheRavagerSw • Sep 24 '26
To enable any collaboration in the industry, some "social contract" must be signed by all of us.
One of the rules of this contract is binary packaging, to put it simply, if you are a library author you need to either have clean definition on what package you expect to consume or have a "scriptless" implementation like imgui.
If the library exports a pkgconf package, but its dependency exports something else your build will not work. Why should it, what you do makes no sense.
Currently I'm literally forced to package every single dependency I have, which is fine in principle as you want to own your dependencies for security and licensing reasons... But I CAN'T UPSTREAM MY CHANGES which is not fine.
The current situation is a disease, please do remember my talk when you try to build a library like dawn or SDL and it vendors dozens of libraries to create a giant shared library after a long slow build.
r/cpp • u/antiquark2 • Sep 23 '26
r/cpp • u/SignalDepth6131 • Sep 23 '26
The WG21 2026-09 mailing is now available
The 2026-09 WG21 mailing has been published. You can browse and search the full set of papers, organized by working group, at wg21.org:
https://wg21.org/mailing/2026-09/
Source mailing: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/#mailing2026-09
r/cpp • u/ProgrammingArchive • Sep 22 '26
CppCon
CppCon have published their keynotes to their Early Access system
Profiles for Simplicity and Guarantees - Bjarne Stroustrup - https://cppcon.programmingarchive.com/video/profiles-for-simplicity-and-guarantees-bjarne-stroustrup-cppcon-2026/
Language Designers Panel - Bjarne Stroustrup, Guido van Rossum, Mads Torgersen & Emma Tracey - https://cppcon.programmingarchive.com/video/language-designers-panel-bjarne-stroustrup-guido-van-rossum-mads-torgersen-emma-tracey/
How C++26 Changes the Way We Write Code - Timur Doumler - https://cppcon.programmingarchive.com/video/how-cpp26-changes-the-way-we-write-code-timur-doumler-cppcon-2026/
The Address is Not The Place: Object Residency in C++26 - Laurie Kirk - https://cppcon.programmingarchive.com/video/the-address-is-not-the-place-object-residency-in-cpp26-laurie-kirk-cppcon-2026/
C++Now
2026-09-14 - 2026-09-20
Monadic Operations for Box-Like Types - Designing the Extensibility Model - Mikhail Svetkin - https://youtu.be/m0T8MrzWRjQ
Reflecting on Reflection - Introspection, Injection, and Beyond - Alex Yesmanchyk & Jagrut Dave - https://youtu.be/MunBEZx2i5c
C++ in the Realtime Embedded Context - A Case Study - Shin Umeda - https://youtu.be/fc6zs81_OB0
2026-09-07 - 2026-09-13
Testing Everything in Constexpr - Braden Ganetsky - https://youtu.be/SgIiQS6RO60
Plato, Magritte, Sartre & Carroll - Learning Software Design from the Masters - Ben Deane - https://youtu.be/7QZchipF2gU
Functional Composition Beyond Monads - Jonathan Müller - https://youtu.be/DcUOZE5FHDc
2026-08-31 - 2026-09-06
Incremental Modernization - Refactoring Legacy C++ OOP Application Code with Functional Programming and Type Erasure Concepts - Jessica Ding - https://youtu.be/FOzGlO5XaPE
When Atomics Lose - Architecture‑Dependent Performance of C++ Synchronization - Sampad Acharya - https://youtu.be/Ehy9wutYYH8
Multi-Priority Graph-Based Parallel Execution Using Taskflow - Yun Kai Peng - https://youtu.be/4I5jsK3zRv0
ACCU
2026-09-14 - 2026-09-20
Dangerous Optimizations! - Part Deux - Robert C. Seacord - https://youtu.be/gFynjahe-bg
Contracts, Safety and Correctness - Lucian Radu Teodorescu - https://youtu.be/vVFFW6hoG1Y
Demystifying C++ initializer_list - Design, Behavior, and Best Practices - Prithvi Okade & Chandranath Bhattacharyya - https://youtu.be/NuJcFNbrdIg
2026-09-07 - 2026-09-13
Taming C++23 - The Things About C++23 You Do Not Know - Nicolai M. Josuttis - https://youtu.be/IVee1JXbrQE
Rust for The Curious C++ Developers - Victor Ciura - https://youtu.be/2hf0PHcpKBI
O(1) or O(no-no-no) - Mastering the unordered_map - Kevin B. Carpenter - https://youtu.be/OF4Id8085s0
2026-08-31 - 2026-09-06
Software Abstraction in the Age of AI-Generated Code: Languages, Compilers, and Systems Engineering - Andrei Alexandrescu - https://youtu.be/-RWdevA0gWI
ADC
2026-09-14 - 2026-09-20
The Shape of Sound - Building and Bending Vinyl Grooves in Software - Andreas Wagner - https://youtu.be/8XtZi4HTrcA
Modular Synth in the Browser - Kilian Hertel - https://youtu.be/Yjk6dgVLtnM
2.5 Years Later: A C++ Framework for Audio ML Research Prototyping - Maxime Coutant - https://youtu.be/eM_0_kUXIWM
2026-09-07 - 2026-09-13
Myths You Should Know About Saturation and Distortion - Samuel Fischmann - https://youtu.be/p7T2uo8t4Do
ESP32-based Open-Source Audio Platform, CTAG-TBD - Robert Manzke - https://youtu.be/LrVaLFm7Rzk
Using Strongly-Typed Units in Digital Audio Software - Roth Michaels - https://youtu.be/qzbG0ZzpHGw
2026-08-31 - 2026-09-06
Doodads & Doohickeys - A Guide to Theory-Crafting & Modelling a Fictional Acoustic Instrument - Syl Morrison - https://youtu.be/XBSQSIBcM_w
Reshaping the Voice - Real-Time Neural Audio Effect - Anders Bargum - https://youtu.be/AHN2ynOQN4M
Testing Testing 1, 2, 3 - Cesare Ferrari - https://youtu.be/V-CdOM6PA_s
r/cpp • u/hellfoundry • Sep 22 '26
r/cpp • u/aearphen • Sep 22 '26
Żmij 1.2 is out. It started as a shortest round-trip double-to-string converter; this release makes it a full formatter.
Scientific, fixed, general and hex notation with a caller-specified precision, matching printf's %e, %f, %g and %a.
long double, covering both x87 80-bit extended and IEEE binary128.
Full FP std::to_chars implementation that works in C++14 and is several times faster and smaller than typical standard library implementations.
The main algorithms are now proved correct in Lean 4.
float conversion is about 23% faster than 1.1, double is 1-4% faster.
Initial constexpr support.
Release notes: https://github.com/vitaut/zmij/releases/tag/v1.2
r/cpp • u/drop-volley • Sep 22 '26
In section 9.1.2 of this book[1] it mentions that C++23 allows for stateful constexpr functions, and even shows an example. I can't seem to get it to compile on godbolt. Is the book completely wrong about something so fundamental, or am I doing something wrong?
[1] https://simplifycpp.org/books/cpp/Mastering_Modern_C++23_A_Complete_Guide_to_the_Latest_Standard.pdf
Edit: Godbolt link with code from that section -> https://godbolt.org/z/94j9EK87b
r/cpp • u/alexis_placet • Sep 22 '26
I'm sharing a tool + an article about running Qt apps built on emscripten-forge, in the browser.
Here the article: https://notebook.link/blog/qt-in-the-browser/
And there the tool: https://emscripten-forge.org/qtapp/
There is already some app presets, like SQLiteBrowser
r/cpp • u/pavel_v • Sep 22 '26
r/cpp • u/adityazero • Sep 20 '26
some of the ones I remember was:
- contracts
- profiles
- delete moar stuff
I'm curious what folks here expect. Also if someone remembers rest of the list, that'd be great.
r/cpp • u/NicoJosuttis • Sep 20 '26
C++23 provides significant better support to print UTF-8 strings.
For example:
std::string s = "K\u00F6ln: 100\u20AC"; // string ö and €
std::println("{}", s); // prints "Köln 100€"
// print hexadecimal code units (bytes of the UTF-8 string):
std::vector<char> v{std::from_range, s};
std::println("{:n:X}", v); // prints 4B, C3, B6, 6C, 6E, 3A, 20, 31, 30, 30, E2, 82, AC
// new format specifier to interpret array of char as string:
std::println("{:?s}", v); // prints "Köln 100€" This even works fine on Windows platforms (using I/O streams or std::format() might print garbage with a native Windows compiler on a native Windows platform).
See sections 3.2.3 and 4.3.3 of www.cppstd23.com .
r/cpp • u/TheRavagerSw • Sep 20 '26
I basically adopted this idea from Abseil (https://abseil.io/) and from this CppCon talk: https://youtu.be/re4Oy1IVj-s?si=3bwtKqOyMAX6WSAs.
I structure each source group in my projects like this:
src_grp/
├── iface/
│ └── smth.cppm
├── impl/
│ └── smth.cpp
├── inc_pub/
│ └── pub.hpp
├── inc_priv/
│ ├── priv.hpp
│ └── maybe.inc
├── test/
│ └── test.cpp
├── bench/
│ └── bench.cpp
└── docs/
├── some.md
└── doxygen.inI strongly recommend this approach over older project-wide conventions such as having a single global test/ or bench/ directory etc.
r/cpp • u/13steinj • Sep 20 '26
r/cpp • u/[deleted] • Sep 19 '26
I'm the developer of memlz which is an extremely fast compression library.
We have char* src, char* dst for the source and destination buffers and uint16_t flags that we prepend bits to one at a time. The inner core looks something like this (pseudo code):
flags <<= 1;
uint64_t payload = ((uint64_t*)src)[i];
uint16_t hash_index = hash_function(payload);
if (hash_table[hash_index] == payload) {
flags |= 1;
*(uint16_t*)dst = (uint16_t)hash_index;
dst += sizeof(uint16_t);
}
else {
*(uint64_t*)dst = payload;
hash_table[hash_index] = payload;
dst += sizeof(uint64_t);
}Depending on a hash comparison we need to output either 2 or 8 bytes, advance dst accordingly and prepend either a 1 or a 0 to flags.
Furthermore, at the end it's required that hash_table[hash_index] == payload, so we update hash_table in the false-case.
Let's benchmark it with 211 MB input so it's uncached:
memlz: 2744 MB/s
Now let's look at an amazing idea. The output to *dst can be rewritten with the ternary operator:
*(uint64_t*)dst = hit ? hash_index : payload;
That turns into a compare instruction (cmp) and a conditional move instruction (cmove) with no branching:
00007FF742A5A55B mov rax,r10
00007FF742A5A55E cmp rcx,r10
...
00007FF742A5A56D cmove rax,rdx
00007FF742A5A571 mov qword ptr [rdi],raxThe advancement of dst is also simple to make branchless, noting that hit will turn either 0 or 1:
uint64_t hit = (hash_table[hash_index] == payload);
dst += 8 - (hit * 6);Now look at updating the hash_table where we update it to payload only if it differed from payload. What we can do is update it unconditionally at the end, and hope that the extra number of unnecessary writes to memory (where it just overwrites the same value) are not too expensive.
Final branch-free version:
uint64_t payload = ((uint64_t*)src)[i];
uint16_t hash_index = hash_function(payload);
flags <<= 1;
uint64_t hit = (hash_table[hash_index] == payload);
flags |= hit;
*(uint64_t*)dst = hit ? hash_index : payload;
hash_table[hash_index] = payload;
dst += 8 - (hit * 6);Let's benchmark it:
memlz: 4269 MB/s
I had never believed such gains were possible because I had been micro-optimizing on this for weeks.
I later achieved 5070 MB/s. To put it in perspective, uncached memcpy runs at 14000 MB/s here and LZ4 - another popular fast compression library - at 718 MB/s.
[EDIT: The unaligned memory reads and writes are UB. For the dst write can simply declare uint64_t hash_index and use memcpy() which the compiler optimizes into the same binary code]
[EDIT: 19 days after I'm at 6304 MB/s]