C++ Logo


Advanced search

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

From: Victor Khomenko <victor.khomenko_at_[hidden]>
Date: Tue, 8 Sep 2020 10:37:50 +0000
Hi Arthur,

What you suggested is one of the workarounds I described in the original posting - it works for Motivating Example 1 but not for Motivating Example 2. The problems are:

  * If you wish to re-use the visitor, you need a mechanism to update the captured reference, and you must remember to update it every time you call the visitor, and there can be many call sites.

  * If the variant is an rvalue, you end up holding two references (of different types) to the same object, so you either forfeit rvalue-ness or break the unique ownership semantics.

E.g. think of AST processing, e.g. for C-like expressions, where AST nodes are variants with a few dozen alternatives, and the visitor applies basic simplifications, like evaluating constant sub-expressions, etc. The visitor has many operator()s, and some of them re-use the visitor by calling it recursively on children nodes (the visitor usually carries some context, so re-use is necessary).


Received on 2020-09-08 05:41:23