Things C++26 define_static_array can't do

· coding · Source ↗

TLDR

  • C++26’s define_static_array simplifies compile-time array persistence but can’t handle non-structural types, string-literal pointers, move-only types, or mutable static arrays.

Key Takeaways

  • The “constexpr two-step” workaround (compute a vector at constexpr time, copy into a fixed-size array) predates define_static_array and remains more general in several cases.
  • define_static_array is limited to structural types because it relies on std::meta::reflect_constant, which is defined via template non-type parameters (NTTPs).
  • Arrays of const char* pointing to string literals, optional<int>, string_view, and span all fail with define_static_array but work with the two-step.
  • The function returns a span<const T> over rodata; producing a mutable constinit static array is architecturally impossible with this API.
  • Barry Revzin’s P3380R1 (Dec 2024) proposes letting programmers mark types as explicitly structural, which would fix the non-structural-type, pointer, and move-only gaps if accepted.

Hacker News Comment Review

  • Commenters broadly read this as another instance of C++ accreting complexity: a new standard feature that requires knowing its own predecessor workaround to understand its limits.
  • A D-language comparison surfaced: Walter Bright showed that immutable int[] aaa = f() in D statically allocates the array in the object file without any two-step ceremony, landing as implicit criticism of C++’s design path.
  • One commenter raised a social note about the author’s standing in the C++ community, which drew more engagement than any technical point and sits outside the article’s technical substance.

Notable Comments

  • @WalterBright: Shows D handles the same constexpr-to-static-array case in two lines, with the object file confirming static allocation, no two-step required.
  • @Pesthuf: “Everything is just an accident, some random pattern randomly discovered by someone when some typo happened to compile.”

Original | Discuss on HN