C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Halfway between 'variant' and 'any'

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 2 Jan 2023 12:02:20 -0500
On Mon, Jan 2, 2023 at 11:39 AM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> It would be very useful to have a class that is halfway between 'variant' and 'any'. What I want is a class with the versatility off 'any' except that it allocates on the stack rather than on the heap.
>
> A few months ago I proposed an alteration to the 'variant' class which would allow it to be used as a pointer to a common base class which is shared by all the specified derived classes. I proposed back then that you would define an object as follows:
>
> variant_common_base<Base,Derived1,Derived2> my_object;
>
> The drawback here is that the translation unit containing the definition of 'my_object' must be aware of, and contain the definitions of the classes, Derived1 and Derived2. Also in the future if we add a third derived class, we must revise the definition of 'my_object' as follows:
>
> variant_common_base<Base,Derived1,Derived2,Derived3> my_object;
>
> Well with the new class I'm proposing today, which I call 'derivative', you simply specify the base class:
>
> derivative<Base> my_object;
>
> Then you can use it to host any object which satisfies the following two criteria:
> (1) The object publicly inherits from Base
> (2) The object size is no greater than 4 * sizeof(Base) -- you can customise this limit

This is not a solution to the problem you outlined. The solution to
the problem you outlined is to create a `sized_any<sz, a>` where `sz`
is the maximum size and `a` is the maximum alignment. You can shove
any type `T` into it so long as it has a compatible size/alignment.

I don't know why you want to bring base classes into this. The problem
doesn't care about base classes. The "versatility of `any`" is that it
can store *anything*. If you want to retrain the "versatility of
`any`", there is no specific need to bring base classes into this.

This really feels like you're trying to justify a particular solution
by defining that it solves a certain problem.

Received on 2023-01-02 17:02:31