r/cpp • u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting • Apr 28 '26
Things C++26 define_static_array can’t do
https://quuxplusone.github.io/blog/2026/04/24/define-static-array/
43
Upvotes
View all comments
Show parent comment
3
u/friedkeenan Apr 29 '26 edited Apr 29 '26
Yeah, you can't declare a
std::vectorasconstinitbecause then you'd have a heap allocation escaping a constant expression. If you don't need it to beconstinitthen you could use thestd::from_rangeconstructor withstd::define_static_arraylike this, but yeah that's not necessarily ideal.Maybe you could do something cursed with a
std::variantor the like where once you perform a mutating operation it switches the underlying type from an array to a vector. That'd be funny.EDIT: Hmm, you know what, you might be able to make your own
constinit_vectorwhich will initialize its pointers likeWhere it signals that it's in the "static" state with the nullptr value for
_allocation_end, and then once you do a mutating operation it can check that and copy over the data to the heap and go on as normal.Still funky, but it fits in the same space as a normal vector and you can write it yourself.