C++ Logo

std-proposals

Advanced search

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

From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>
Date: Tue, 15 Sep 2020 14:08:09 +0200
wt., 15 wrz 2020 o 11:56 Victor Khomenko via Std-Proposals
<std-proposals_at_[hidden]> napisaƂ(a):
>
> 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?
>

One important thing, if this tag have variant inside it, then it
should be tempted by it like:
```
template<typename Var, size_t Index>
struct variant_tag
{
   using ValueType = std::variant_alternative_t<Index,Var>;
   Var& get_variant();
   ValueType& get(); //asset(get_variant().index == Index)
};
```

>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2020-09-15 07:08:23