C++ Logo

std-discussion

Advanced search

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

From: Jefferson Carpenter <jeffersoncarpenter2_at_[hidden]>
Date: Sat, 22 Aug 2020 13:11:11 +0000
On 8/21/2020 2:06 PM, Victor Khomenko via Std-Discussion wrote:
> Dear all,
>
> [I searched the list's archive but didn't find anything relevant.]
>
> Problem: How to change the value of a variant from within a visitor? Unfortunately, there is no straightforward way to do that, as the relevant operator()(Alternative&) of the visitor has no access to the enclosing std::variant.

Two thoughts:

1) Add a reference to the variant to the constructor of the visitor, and
write

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

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).


Do either of those work?

Jefferson

Received on 2020-08-22 08:14:39