C++ Logo

std-proposals

Advanced search

Re: [std-proposals] [DRAFT PAPER] std::variant with std::specify_base

From: Bengt Gustafsson <bengt.gustafsson_at_[hidden]>
Date: Sun, 25 Sep 2022 19:59:39 +0200
Instead of using an ill-suited class such as std::variant to store an
instance of one of a set of subclasses and require std::variant to get a
new method to handle this situation better I think that a more suitable
way of storing a subclass instance would be inside a polymorphic_value
with SBO buffer of sufficient size.

The only drawback of this would be to define the SBO buffer size just
right to hold the largest subclass. With my new reference implementation
here <https://github.com/BengtGustafsson/PolymorphicValue>you can
specify that SBO buffer overflow is forbidden and get a compile time
error if it is set too low for the intended classes. This is posted as a
variant of P0201 polymorphic_value tp further the debate around that
proposal. Its primary goal is not to forbid heap allocations but with a
closed set of subclasses this can be done .

A type alias which handles a closed set of subclasses size and alignment
needs called polymorphic_value_for<T, SubClasses...> is included in the
latest version for added convenience. I'm unsure if this is important
enough to be standardized though. Enumerating all the subclasses seems
like such an anti-pattern.

Bengt


Received on 2022-09-25 17:59:57