C++ Logo


Advanced search

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

From: Victor Khomenko <victor.khomenko_at_[hidden]>
Date: Mon, 24 Aug 2020 12:39:50 +0000
Thanks Roman,

> std::visit([&](auto&& value) {
> my_visitor(value, the_variant);
> }, the_variant);

This looks like an interesting combination of the workaround I suggested in my original posting and Ville's suggestion to have another visit function that would pass the variant to the visitor as an extra parameter. If you wrap this code into a function, it will boil down to an implementation of Ville's suggestion.

I think this works in practice, but the question is whether it's more elegant than a function casting an alternative to a variant:
  * You don't std::move or std::forward the variant and the alternative, even if the variant is an rvalue. This loses rvalue'ness of the argument, but I agree that it would be potentially dangerous to have two rvalue references to the same object, as the ownership should be unique (you'll have the same problem even if one of the references is lvalue).
  * All operator()s in the visitor class must now accept an extra argument, even if only few need it.

We discussed these with Ville in this thread, so you could have a look if you wish.


Received on 2020-08-24 07:43:20