C++ Logo

std-proposals

Advanced search

Re: [std-proposals] inplace_vector failable apis

From: Barry Revzin <barry.revzin_at_[hidden]>
Date: Mon, 20 Nov 2023 11:13:12 -0600
On Mon, Nov 20, 2023, 10:21 AM Jonathan Wakely via Std-Proposals <
std-proposals_at_[hidden]> wrote:

>
>
> On Mon, 20 Nov 2023 at 00:32, Magnus Fromreide via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> Hello!
>>
>> When I saw the failable API's the first question I asked myself was why
>> you
>> choose to use T* as return type rather than
>> std::optional<std::reference_wrapper<T>> or possibly
>>
>
> That would look pretty silly if we get std::optional<T&> in C++26. Working
> around the absence of optional<T&> like this would be a pretty ugly kluge.
>
> If we do get optional<T&>, I think it would be reasonable to ask why it's
> not used there.
>

optional<T&> is the clearly superior choice for return type here. To the
point where it's worth rejecting the inferior API until we get it.

But T* is itself better than optional<reference_wrapper<T>>. It's half the
size (8 bytes instead of 16). And it's more ergonomic: you can write if (p)
p->f() with a pointer (or optional reference), but with an optional
reference_wrapper you'd have to write if (p) p->get().f(). The same applies
to other function calls - g(*p) might work for a T* but not for
optional<reference_wrapper<T>> due to constraints, so that's more uses of
get() there too. Not a great user experience.

Barry

>

Received on 2023-11-20 17:13:26