TGViewer
C++ - Reddit C++ - Reddit @r_cpp · 230 subscribers
Post #25443 21
immutable<>, complement of C++26 std::indirect<> and std::polymorphic<>

C++26 introduces [`std::indirect<>` and `std::polymorphic<>`](https://wg21.link/p3019) (reference implementation at [github.com/jbcoe/value_types](https://github.com/jbcoe/value_types/)):

* `std::indirect<T>` is like a value-minded `std::unique_ptr<T>` sans polymorphism support. `std::indirect<T>` is movable if `T` is movable and copyable if `T` is copyable.
* `std::polymorphic<B>` is like a value-minded `std::unique_ptr<B>` for polymorphic bases `B`. `std::polymorphic<B>` can hold an object of any copyable class `D` which is an instantiable subclass of `B`. `std::polymorphic<B>` is copyable; its copy constructor will polymorphically clone the underlying object.

Both types are designed to be non-nullable. For lack of destructive move semantics, both have a moved-from state which can be identified with the `valueless_after_move()` member function.

As far as I can tell, the design of these is based on Sean Parent's "concept–model idiom". Remembering his presentation on the topic (https://sean-parent.stlab.cc/papers-and-presentations/#value-semantics-and-concept-based-polymorphism), I noticed that there is an obvious complement to `indirect<>` and `polymorphic<>` which I provisionally dub `immutable<>`:

* `immutable<T>` is like a value-minded `std::shared_ptr<const T>`. It is cheaply copyable (no deep copy), with no movability requirements imposed on `T`. It can hold an object of any instantiable subtype of `T`.

[Possible implementation + some tests on Compiler Explorer](https://gcc.godbolt.org/z/qh3K3d196)

Does this make sense? I find it very useful for building persistent data structures. In fact, it seems so obvious to me that I'm surprised this wasn't already in P3019.

*Edit:* minor correction

https://redd.it/1u7bamr
@r_cpp
More from @r_cpp
  1. Sep 29, 2026Boost.Graph 1.95 will be C++17 Dear Boost.Graph community, In two release cycles (Boost re…
  2. Sep 26, 2026Token Sequence Injection & Modern Macros: The Most Game-Changing Compile-Time Feature in C…
  3. Sep 25, 2026myStringStream.str("") Considered Harmful Under C++20 I was recently looking at some (rath…
  4. Sep 20, 2026A clever branch free optimization I'm the developer of memlz which is an extremely fast co…
  5. Sep 15, 2026Inside Boost.PolyCollection https://bannalia.blogspot.com/2026/09/inside-boostpolycollecti…
  6. Sep 11, 2026C++26: Standard Library Hardening Experiments https://www.cppstories.com/2026/hardening-ex…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →