C++ Logo

std-proposals

Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Thu, 15 Sep 2022 21:23:02 -0400
On Thu, Sep 15, 2022 at 5:58 PM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> On Thu, Sep 15, 2022 at 9:33 PM Zhihao Yuan <zy_at_[hidden]> wrote:
> >
> > I agree that variant<monostate, Cat, Dog>
> > can be a model for
> > variant<specify_base<Animal>, Cat, Dog>,
> > but I also want variant<Cat, Dog> to
> > implement an Animal interface.
> > To summarize, I think
> >
> > nonnull
> > nullable
> > throwing
> >
> > All make sense.
> >
> > How about this:
> >
> > template<class T>
> > struct implements
> > {
> > template<class... Ts>
> > using model = std::variant<Ts...>;
> > };
> >
> > template<class T>
> > struct implements_nullable
> > {
> > template<class... Ts>
> > using model = std::variant<std::monostate, Ts...>;
> >
> > static auto default_proxy() noexcept { return nullptr; }
> > };
> >
> > template<class T>
> > struct implements_or_throw
> > {
> > template<class... Ts>
> > using model = std::variant<std::monostate, Ts...>;
> > };
>
>
> It isn't immediately apparent to me how you would use those. Something
> like the following?
>
> implements<Animal>::model<Dog,Cat,Fish> obj;
>
> obj->Eat();
>
> The whole point of my proposal is to have this simple syntax:
> obj->BaseClassMethod();

My question, which isn't explained in the proposal, is this: why do we
want it to be that easy?

If a standard library type supports a particular operation, then that
means that we're saying (in theory) that this is a good and useful
thing for C++ programmers to have and use. So... is it?

This feels a bit like you want the benefits of variant-based
polymorphism (ability to use value types directly, no type-erasure
like `any`, etc), but you don't want to use interfaces based on
`visit` or helper functions that aren't member functions of some type.
That is, you really want to use member functions to define your
interface, but the only way to do that is with a base class, but that
comes with a bunch of problems, so you want to make `variant` solve
those problems.

Received on 2022-09-16 01:23:56