C++ Logo

std-proposals

Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 14 Sep 2022 15:26:39 -0400
On Wed, Sep 14, 2022 at 3:15 PM Lénárd Szolnoki via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Hi,
>
> I don't like that this is implemented as essentially a specialization of variant. There is no reason that variant<Cat, Dog> and variant<specify_base<Animal>, Cat, Dog> should be different types. They are essentially the same thing with the same layout. If you have distinct interfaces that specify these two types, then you might end up needlessly moving or even copying when gluing them.

Well, there is a reason for this: it allows overloading `operator->`
to access it. By explicitly specifying a type, you can create a single
overload for that operator which returns a pointer to that specific
type. If the type has to be computed, that would cause a problem if
the `Ts` have multiple common bases.

That having been said, I agree that a facade would be preferable, some
type that references the variant and applies a specific base class
test to them.

> At most this should be a facade over variant, with access to the underlying variant, when needed. But I prefer a convenience function over a variant even more.
>
> As for the implementation I believe there could be potential cv-correctness issues if varant holds cv-qualified alternatives. I believe variant<const Cat, Dog> is valid, you should not be able to get a non-const Animal pointer out of this.
>
> Finally this whole thing feels a bit wrong for me. This is a weird mixture of two kinds of dynamic polymorphism when one would be enough. In the end you pay for both kinds of dynamic dispatch, although hopefully the compiler can optimise the virtual call out. Even then, why pay both for a type discriminator plus a vtable pointer when you (hopefully) don't even use the vtable pointer?

I agree that the motivation section needs to be beefed up with more
than what amounts to a declaration that people want to avoid dynamic
allocations. I mean sure, they want to do that, but why are they using
base class polymorphism? As you point out, having both a vtable
pointer and a type discriminator in the object's storage isn't helping
in RAM-limited systems.

Received on 2022-09-14 19:27:33