C++ Logo

STD-DISCUSSION

Advanced search

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


Thanks Jefferson,

> std::visit(Visitor { variant }, variant);

This resembles the workaround that I described in my original posting. It works, but has problems, especially if one wishes to reuse the visitor (e.g. apply it to every node in a tree recursively):
  * you'll need mechanism to update the stored pointer to variant (can be mitigated by inheriting visitors from a class that manages pointer to variant);
  * you must remember to update the stored pointer before every call to std::visit, or you get an inconsistent state when the alternative is from a different variant (can be mitigated by creating a function that updates the pointer before calling std::visit, but you need to remember to use it consistently instead of std::visit);
  * it is not clear how to pass the variant by rvalue reference - note that inside the visitor's operator() you'll have access both to the variant and to its alternative, i.e. two references (with different types) to the same object, i.e. shared ownership.

A function converting an alternative to a variant seems a much neater solution.


> 2) Use `overloaded` as described here
> https://en.cppreference.com/w/cpp/utility/variant/visit
>
> So that you can write a lambda for each case and capture the variant for
> the appropriate one(s).

This works if the variant has few alternatives and is not reused, but otherwise this becomes unwieldy.





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

Older Archives on Google Groups