C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Use optional<T> as though it were T

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Tue, 4 Jul 2023 18:16:57 +0100
On Tue, Jul 4, 2023 at 5:30 PM Thiago Macieira wrote:
>>
> > This may sound like an over-simplification, but what if the 'dot'
> > operator and the 'arrow' operator were swapped for a new type
> > "std::optional_direct".
>
> And what happens if T has operator->()?


You didn't read the last line of my previous post. (Or maybe you did
and are just emphasizing the point).

Okay here's another possible way of doing it:
(1) In order to access member functions/variables of T, use the 'dot' operator
(2) If you apply the "->" operator to an "std::optional_direct", then
it's as though you applied the arrow operator to T

So that leaves just one thing to solve: How do we access member
functions/variables of "std::optional_direct" such as "emplace" or
"has_value". Well maybe they could all be static functions instead of
member functions. As follows:

std::optional_direct<std::string> g_obj;

std::optional_direct< std::vector<std::string>::iterator > g_it;

int main(void)
{
    std::optional_direct::emplace(g_obj, "Hello World"); // 'emplace'
is a static member function

    g_obj.c_str(); // This invokes 'c_str()' on the std::string object

    std::vector<std::string> myvec(1u);

    std::optional_direct::emplace( g_it, myvec.begin() ); //
'emplace' is a static member function

    g_it->c_str(); // Not a problem when arrow is overloaded --
invokes '->' on the iterator object
}

Received on 2023-07-04 17:17:10