C++ Logo


Advanced search

Re: std::variant - going from Alternative& to the enclosing variant&

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Tue, 15 Sep 2020 16:12:46 +0300
On Tue, 15 Sep 2020 at 12:56, Victor Khomenko via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> And to push it even further: If only some operator()s require access to the variant (a common case), one can avoid typing "variant_tag" and specify the types of alternatives instead (i.e. as usual), on the pick-and-mix basis. This is due to implicit conversion of variant_tag<> to the type of the alternative, so does not require extra complexity - std::visit would always create a variant_tag, which is then converted if necessary. That is, extra typing is required only if operator() needs access to variant, otherwise the visitor is exactly as it was before:
> struct Visitor{
> // does not need access to variant,
> // so looks as usual
> void operator(string& t) { ... }
> // needs access to variant
> void operator(variant_tag<1> t) { ... }
> };
> Another advantage is that the visitor can now distinguish between different occurrences of the same type in the variant's parameters.
> Ideally, one still needs interface using types as well as indices, i.e. the variant_tag template could accept both an index parameter and a type parameter, and provide an implicit conversion to a similar template that accepts only the type parameter (as well as the conversion to the type of alternative). Then std::visit could create an instance of variant_tag<index,std::variant_alternative_t<index,my_variant>> and call a visitor on it.
> I think it is worth creating a proposal - what do people think? I wouldn't do it alone, since the main idea is not mine, and I have no experience of writing proposals. Any volunteers to join?

For what it's worth: the implementation of a std::variant provides
indexed visitation internally - that is, it passes the index
of the variant member into internal visitors. Exposing such
functionality to users seems like a fairly easy stretch of

Received on 2020-09-15 08:13:00