C++ Logo

std-proposals

Advanced search

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

From: Victor Khomenko <victor.khomenko_at_[hidden]>
Date: Tue, 15 Sep 2020 09:55:59 +0000
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?


Received on 2020-09-15 04:56:08