HeadlinesBriefing favicon HeadlinesBriefing.com

C++26 Adds std::is_within_lifetime for Compile-Time Union Checks

Hacker News •
×

C++26 introduces std::is_within_lifetime, a consteval function that checks whether a union member is currently active during compile-time evaluation. The function, added to the <type_traits> header, returns true if the pointed-to object is within its lifetime, making it invaluable for constexpr programming scenarios where undefined behavior must be avoided.

This addition addresses a long-standing problem in C++: determining which union member is active without reading it directly, which would trigger undefined behavior. The function takes a pointer rather than a reference to avoid complications with temporary objects and lifetime extension rules. While primarily designed for union member checking, the committee chose a general name to allow broader applications in constant evaluation contexts.

The feature originated from a practical need: implementing an Optional<bool> with minimal storage overhead. Before C++26, developers had no standard way to check union member activity at compile time, forcing awkward workarounds. With std::is_within_lifetime, the solution becomes straightforward—use the function during consteval contexts and fall back to sentinel values at runtime. As of February 2026, major compilers haven't implemented this feature yet, but it represents a significant improvement for constexpr programming safety.