Skip to content

add a value_or_eval similar to boost::optional #54

@malcolmdavey

Description

@malcolmdavey

Hi TL
Thanks for your great library.

Was wondering if you had considered a value_or_eval, similar to the existing value_or, which returns the current value if it exists, or returns value from a lambda etc, but only executes if the optional is empty.

The point is to enable lazy evaluation, especially for expensive calculations.

(This exists in boost::optional, but not sure if there was a reason not to include it in the std.)

Thanks.

Here is a implementation from boost 1.61 for example

    template <typename F>
    value_type value_or_eval ( F f ) const&
      {
        if (this->is_initialized())
          return get();
        else
          return f();
      }
      
    template <typename F>
    value_type value_or_eval ( F f ) &&
      {
        if (this->is_initialized())
          return boost::move(get());
        else
          return f();
      }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions