C++ Logo

std-proposals

Advanced search

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

From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>
Date: Fri, 11 Sep 2020 01:49:17 +0200
czw., 10 wrz 2020 o 16:27 Victor Khomenko via Std-Proposals
<std-proposals_at_[hidden]> napisał(a):
>
> > You want to pick an
> > example where you can without additional round-trips take the pattern
> > displayed in that response and map it back onto your actual codebase. I
> > hope — but am not confident! — that your new example clearly
> > demonstrates the problem you're asking about, and that therefore my
> > solution will help you.
>
> This is not about solving a problem - my code already works. This mail list is to propose and discuss the additions to the C++ standard. I wrote a lot of code for ASTs, and variants generally seem a good fit for AST nodes. However, I noticed that the problem I described in the original post is rather common and very annoying - one tends to write a big chunk of the visitor, then at some point the node's alternative needs changing, so one has to go back and uglify the code using some workaround. It's so-o-o tempting to use a cast!
>
> I think adding the variant_from_alternative function to the standard is the best solution. Of course, there are workarounds, and I already used them in my code. However, these workarounds result in less-than-elegant and sometimes fragile code (as illustrated in my example).
>

One thing, why do you not implement `variant_from_alternative`
yourself? If standard can do it, then you can do it too.
This means this discussion should start with you presenting a function
that solves your problem and then arguing that it should be part of
the standard.
If you can't do it then is it possible for a standard library to do it
correctly? Probably the only exception from this is changing internal
representation/implementation of a given type.
Of course quality of your implementation is not need to be up to
standard quality level and handle all possible use cases, it should
hande correctly your code and not something like:

> However, these workarounds result in less-than-elegant and sometimes fragile code

Simply, the difference should be:
```
my::special_fucn(...);
//and
std::special_fucn(...);
```

Many times when I implement something I create multiple helper
functions that solve some hard problems like this.
Sometimes I even reimplement some standard functions because default
one does not give me all the invariants that my code needs.

Received on 2020-09-10 18:52:59