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: Wed, 5 Jul 2023 10:45:32 +0100
On Tue, Jul 4, 2023 at 8:10 AM Harald Achitz wrote:
>
> Wouldn't it make more sense to have a (new) optional with a different operator dot behavior?
>
> n4477.pdf (open-std.org)


Let's say we have a class called 'Laser' with 5 methods that are all
pure virtual. One of these methods is "void Trigger(void)".
The class 'NitrogenLaser' inherits from 'Laser', and the class
'NitrogenPicoLaser' inherits from 'NitrogenLaser'.

In the implementation of "NitrogenPicoLaser::Trigger", we invoke the
base class's method as follows:

    void NitrogenPicoLaser::Trigger(void)
    {
        this->NitrogenLaser::Trigger();
        // Do some more stuff here
    }

So we already have an established syntax here whereby we can select
the 'owner' of the method we're calling.

So why not use this same syntax for Stroustrup & Dos Reis's idea of
overloading "operator.", and also for my own idea of having
"std::optional_direct" ? That is to say, you can access the member
variables/functions of the holder class as follows:

    std::optional_direct< std::stringstream > obj;
    obj.optional_direct::emplace();

    if ( obj.optional_direct::has_value() ) DoSomething();

Alternatively, if we don't want to have to repeat the name of the
class verbatim, we could just write 'class' instead of the class's
name, as follows:

    obj.class::emplace();

Or another option would be to use a global function to give us access
to the holder class:

    std::direct(obj).emplace();

or maybe even have an operator '(class<obj>)' that you would use as follows:

    std::optional_direct< std::stringstream > obj;
    (class<obj>).emplace();

    if ( (class<obj>).optional_directhas_value() ) DoSomething();

Received on 2023-07-05 09:45:44