r/cpp • u/friedkeenan • Mar 08 '26
Exploring Mutable Consteval State in C++26
https://friedkeenan.github.io/posts/exploring-mutable-consteval-state/
83
Upvotes
r/cpp • u/friedkeenan • Mar 08 '26
View all comments
Show parent comment
3
u/friedkeenan Mar 09 '26
Thanks for calling it impressive, it's something I was really excited to figure out and share.
I'm not precisely sure what you mean here, but theoretically you can actually refer to previous state of a
consteval_state. You would just need to do likemy_state::get(previous_index)or whatever. But I guess if you mean like the following:Then you can do that too with a
consteval_state, you would just need to use your own state, not theloop_statefromexpand_loop, and push a previous state value to it.I'm again not sure what exactly you mean, sorry. But I would say that there may be some less-than-intuitive behavior regarding the order of evaluation, depending on how you have your
constevalblocks set up. So if you're more particular about separating out yourconstevalblocks, then you might be able to get what you want.And yep, this was just a placeholder for actual error-handling stuff that I just didn't want to bother with so that I could focus on the functionality. A real exception or some other error handling method would definitely be better here for more rigorous code.
I do this regularly, actually, and did it intentionally here. For me at least, it reduces slightly what my brain needs to think about when reading code back. If I were to see just
if (index == 0)then for a split second my brain might go "But what ifindexis negative?" before quickly realizing that it can't be. Whereas withif (index <= 0)my brain just immediately picks up on the intention of only letting positive values through.It's a very slight benefit, but it exists for me. It's also nice that it will then be consistent with cases where
indexcould theoretically be negative, which does happen.And yeah, unfortunately GCC currently doesn't play nice with the trick we rely on for
consteval_state::has_inserted_at. Near the end of my blog post I show a version which does work with it, but you need to provide the indices yourself: https://compiler-explorer.com/z/MoEor1a5G