C++26: Constexpr Virtual Inheritance
14 hours ago
- #virtual-inheritance
- #constexpr
- #C++26
- C++11 introduced constexpr with strict restrictions, allowing only single return statements in functions.
- C++14 relaxed constexpr, permitting local variables, loops, and multiple statements.
- C++20 expanded constexpr support to include dynamic allocation, enabling types like std::string and std::vector in constant evaluation, and allowing constexpr virtual functions.
- C++23 allowed static local constexpr variables and try blocks inside constexpr functions.
- C++26 continues to relax constexpr rules, adding support for exception handling during constant evaluation and removing the prohibition on virtual inheritance via proposal P3533R2.
- Virtual inheritance solves the diamond problem in multiple inheritance by ensuring a single shared instance of a base class, though it increases object size and complexity.
- Before P3533R2, constexpr was forbidden for constructors and destructors of types with virtual bases, blocking compile-time usage of such hierarchies.
- P3533R2 enables constexpr member functions and object construction for types with virtual inheritance, facilitating constexpr-ification of standard library components like std::ios_base and streams.
- This proposal unblocks improvements in libraries, such as making streams constexpr, which impacts features like exception types in <chrono> and range-based parsing.
- constexpr is evolving toward being a simple opt-in feature, with fewer syntactical restrictions, moving closer to a model where any function can be constant-evaluated based on evaluation properties.