C++ Logo

std-proposals

Advanced search

Function proposal: generic value_or

From: Roberto Romani <roberto.romani_at_[hidden]>
Date: Sun, 4 Jul 2021 21:32:18 +0200
Dear All

 

I have trivial proposal: a function similar to the std::optional.value_or:
it returns the first parameter not null, if it does not find it, then it
returns a default value. It is very similar to a coalesce SQL function.

The input parameters can be raw pointers, std::unique_ptr, std::shared_ptr,
std::weak_ptr or std::optional.

 

My idea is something like:

 

            /**

     * Concept that define a pointer of type PointerType that points to

     * ValueType.

     * It covers: raw pointers, std::unique_ptr, std:shared_ptr,

     * std::weak_ptr, std::optional, std::null_ptr, NULL, 0 and any other

     * class that has the operators * and bool.

     */

    template<typename PointerType, typename ValueType>

    concept PointerTo = requires(PointerType pointer, ValueType) // pointer
must behave like a raw pointer that points to a ValueType

    {

        {*pointer} -> std::convertible_to<ValueType>;

        {!pointer} noexcept;

    }

    || requires(PointerType pointer, ValueType) // pointer must behave like
a weak_ptr that points to a ValueType

    {

        {*pointer.lock()} noexcept -> std::convertible_to<ValueType>;

    }

    || std::same_as<std::nullptr_t, PointerType> // to cover the case of
null_ptr

    || std::same_as<int, PointerType>; // for NULL (in VS) and 0

 

 

    /**

    * It looks for a not null value in to_test_v. If it does not find it,

    * then value_or returns a default value.

    *

    * \param default_value Value to return if all the values of to_test_v
are null

    * \param ...to_test_v The values to test for not null

    * \return The first value not null of to_test_v, if no value of
to_test_v is not null then default_value

    */

    template<typename T, PointerTo<T>... Args>

    constexpr decltype(auto) value_or(T&& default_value, Args&&...
to_test_v) noexcept;

 

 

There is the concept PointerTo that defines a class that behave like a raw
pointer, and then there is the function value_or that tales a default value
and then a list of "pointers" to check.

 

In PointerType I have included also the possibility the pointer is an int in
order to support the values 0 and NULL, I am not sure that it is needed.

 

I have declared value_or noexcept, I think it makes sense but I do not think
it is possible to guarantee it in a formal way.

 

I think a function like this may help to manage object that can be null in
structured form.

 

Here you can find a possible implementation:
https://github.com/roroberto/cpp_small_simple_stupid_stuff/blob/main/value_o
r/value_or.h

 

 

Best Regards

Roberto

 


Received on 2021-07-04 14:32:22