C++ Logo

std-proposals

Advanced search

[std-proposals] Proposal for std::optional extensions

From: Lorenz Quack <code_at_[hidden]>
Date: Sun, 09 Jun 2024 14:44:56 +0200
Hi std-proposals list,

This is my first submission to this list.

I have three proposal ideas that I would like to float here.
They all concern std::optional.
I have searched the archive of this mailing list and have not found similar proposals.

In the below proposal ideas I will provide some examples that will assume the following code declarations:

    struct Foo {
      int bar;
    };
    
    std::optional<Foo> try_generate_foo();
    
    Foo safe_generate_foo()


Without further ado, here are the proposal ideas:

1. Allow passing pointer-to-member (both data and function member) to std::optional::transform()
   Example:
       // before proposal
       int x = try_generate_foo().transform([](Foo& f){ return f.bar; });

       // after proposal
       int x = try_generate_foo().transform(&Foo::bar);

   This is similar to how the projections of the ranges algorithms allow pointer-to-members to be passed.
   If this proposal idea goes further it should be considered whether the exact same INVOKE semantics [1] should
   apply here.

2. Add the ability to call a function to create a default value.
   This could be in the form of a dedicated function like std::optional::value_or_call(Callable&& c) or an
   overload to optional::value_or
   Example:
       // before proposal
       auto optional_foo = try_generate_foo();
       if (optional_foo.has_value()) {
         return optional_foo.value();
       } else {
         return safe_generate_foo();
       }

       // after proposal
       return try_generate_foo().value_or_call(&safe_generate_foo);

   The name `value_or_call` is obviously a working title and would then need further discussion should this proposal
   idea gain traction.

3. add or_generate(Callable&& c)
   This should return `this` if the optional has a value and otherwise a new optional containing the result of calling
   the callable. This is different from or_else where the callable has to return an optional.
   This is analog to transform and and_then.
   Example:
       // before proposal
       try_generate_foo()
         .or_else([](){ return make_optional(safe_generate_foo()); })
         .and_then(...)

       // after proposal
       try_generate_foo()
         .or_generate(&safe_generate_foo)
         .and_then(...)

   Again, the name `or_generate` is just a working title.



Looking forward to getting some feedback on these ideas.

Best regards,
Lorenz


[1] https://en.cppreference.com/w/cpp/utility/functional#Function_invocation

Received on 2024-06-09 12:44:59