C++ Logo

std-discussion

Advanced search

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

From: Jefferson Carpenter <jeffersoncarpenter2_at_[hidden]>
Date: Wed, 26 Aug 2020 05:45:22 +0000
On 8/24/2020 12:10 PM, Victor Khomenko wrote:
> 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.
>

Just one more question. What is the return value of the visitor?
Instead of modifying the variant inside of the visitor, could you have
the visitor return a signal that the variant should be modified?

-Jefferson

Received on 2020-08-26 00:48:58