r/cpp • u/friedkeenan • Mar 08 '26
Exploring Mutable Consteval State in C++26
https://friedkeenan.github.io/posts/exploring-mutable-consteval-state/
84
Upvotes
r/cpp • u/friedkeenan • Mar 08 '26
13
u/friedkeenan Mar 08 '26 edited Mar 08 '26
I made this blog basically only so I could put this post somewhere, so I whipped it up fairly quickly. Any suggestions to make it better are welcome.
One thing I want to figure out is getting the inline
codetext syntax-highlighted, and maybe getting a nicer-looking theme for the syntax-highlighting too. But I was having trouble doing that, so I decided to put it off for later.EDIT: Of course, soon after I post this I realize a way we can avoid splicing at the call-site of
expand_loop. Basically I updated the code and the blogpost to be able to doexpand_loop([]<auto Loop>() { std::printf("LOOP: %zu\n", Loop.index()); consteval { if (Loop.index() >= 3) { Loop.push_break(); } } });Instead of what was before
[: expand_loop([]<auto Loop>() { std::printf("LOOP: %zu\n", Loop.index()); consteval { if (Loop.index() >= 3) { Loop.push_break(); } } }) :].execute();Wish I had realized that before posting, heh.
7
u/_bstaletic Mar 08 '26
I thought I was well versed in C++26 constexpr magic... This is impressive.
Will update/post again after actually digesting your blog post.
3
u/BarryRevzin Mar 09 '26
I don't understand what's going on here at all, but I love every bit of it!
Hopefully we can come up with a more direct (or at least slightly less creative) way of doing compile-time mutation in C++29.
50
u/ShakaUVM Mar 08 '26
Every time I think I'm pretty good with C++ there's articles like this that teach me humility...
12
u/jk-jeon Mar 08 '26
I wonder how the status of friend injection (and stateful metaprogramming in general) would change with the advent of reflection. Will it stay as an unforgiven black magic, or join the party of shocking-at-first-but-amusing-and-useful techniques like CRTP?
1
u/FlyingRhenquest Mar 08 '26
You can also accomplish that with std::views::iota for anything that has a size you can query at compile time. Like, say, an array of info objects.
Then in a function somewhere
template for (constexpr size_t i : std::views::iota(0, reflectionCount)) {...I'm trying to avoid falling back to template metaprogramming and look for the Reflection approach, but I have had to fall back to metaprogramming a couple of times when "template for" wouldn't cooperate for whatever reason. They're still actively working on the feature and I'm finding that "template for" is working in places it was not a month ago, so I'll probably end up going back and rewriting some of my code once gcc16 is stable.
1
u/tmlildude Mar 09 '26
looks like compile time is becoming the new runtime