-
-
Notifications
You must be signed in to change notification settings - Fork 37
Description
Channel
C++Weekly
Topics
c++26 std::define_static_array and std::define_static_string
Length
5-10 minutes
Rationale
The issues raised in
C++ Weekly - Ep 269 - How To Use C++20's constexpr std::vector and std::string
and
C++ Weekly - Ep 313 - The constexpr Problem That Took Me 5 Years To Fix!
were primarily around getting constexpr calculated data stored in a vector or string at compile time to be available at runtime. The solutions presented boiled down to two main patterns:
- Doing the work twice, once to get the size for the final container, and then again to copy the data into a container with static storage duration of that size.
- Doing the work once, but copying the data twice. Once into a data structure that massively over-allocates, and then from that into the final container of the right size with static storage duration.
Both of these approaches are clunky and full of boilerplate code.
The indicated features of c++26 solve both issues with a call to the standard library, and can be experimented with in godbolt right now using the experimental P2996 clang fork.
Here is an example for a compile time string containing primes up to a limit being made available to runtime.
Old solution: https://godbolt.org/z/q5oefMdWf (String -> Oversized Array -> Array -> Static Array -> String View)
New solution: https://godbolt.org/z/9acdTzj68 (String -> String View)
This completely negates all the patterns we had to struggle with just to get constexpr dynamic ranges into runtime, making this extremely useful for constexpr programming.