C++ Logo


Advanced search

Subject: Re: std::variant - going from Alternative& to the enclosing variant&
From: Victor Khomenko (victor.khomenko_at_[hidden])
Date: 2020-08-24 06:40:54

> > > auto& var = variant_from_element<int, string>(my_arg);
> >
> The problem here is not auto. The problem is knowing what the variant's
> alternative types are. Getting them wrong is a run-time error. If the variant is
> passed in as a parameter, there is no run-time error.

If variants are typedef'ed (plausible due to the natural laziness and unwieldiness of variant type declarations), and the variant type is passed as a template parameter, and instead of auto one uses explicit types, then there is a good chance of catching the error:

  IntendedVar& v = variant_from_alternative<UnintendedVar>(a); // compile time error
  void f(IntendedVar&);
  f(variant_from_alternative<UnintendedVar>(a)); // compile time error

> > * if the variant is passed by rvalue reference, the visitor member functions
> would presumably be declared as
> > ret_type operator()(Variant&& v, Alternative&& a)
> Well, then don't move from the variant if you still need to access its guts.
> That doesn't seem like a massive problem to me.
I'm sure this works in practice, but if the programmer passes an rvalue reference, they presumably would want to move at some point. Also, && means unique ownership, so one should not have two && variables uniquely owning the "same" object (aggravated by these variables having different types, which disguises shared ownership). I'd rather delete this overload altogether - in practice Variant& would usually be used (at least in the described motivating examples).

STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups