C++ Logo

std-discussion

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:10:45 +0000
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.




Received on 2020-08-24 07:14:17