C++ Logo

std-proposals

Advanced search

Re: std::as

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Thu, 5 Nov 2020 15:52:40 -0500
On Thu, Nov 5, 2020 at 12:09 PM Avi Kivity via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> How can the reader of *get_if() tell if the author intended this
> optimization, or was just lazy?
>
Well, we know what *semantics* they intended — "get the value if possible;
otherwise UB." Whether they get the *optimization* is up to the vendor
(but vendors should make the performant choice, please).

Function names should communicate intent. "get_if()" communicates that you
> don't know if the variant holds the the type you are asking for or not.
>
No it doesn't — I mean, not *a priori*. The identifier `get_if` is
completely meaningless a priori — just like std::get and std::visit. The
only way for a programmer to learn what these identifiers mean is to, well,
learn. (I have a Back to Basics talk on algebraic data types I can
recommend!) Once the programmer has learned the idioms around
std::variant, they'll know what *std::get_if "communicates," by definition,
because *std::get_if *is* one of the idioms around std::variant.

Of course, if the maintainer(s) of some particular codebase decide that
they'd like another name for this operation, they can write a named
function:

Target uncheckedGetTarget(const std::variant<Target, Destination>& td) {
    MC_ASSERT(td.index() == 0);
    return *std::get_if<0>(&td);
}

I don't think the standard library ought to bother providing any "middle
ground" between the existing C++17 idiom *std::get_if and the
codebase-specific uncheckedGetTarget.

–Arthur

Received on 2020-11-05 14:52:53