C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Copy-construct, move-construct, and PR-construct

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Wed, 23 Aug 2023 16:38:58 +0100
On Wed, Aug 23, 2023 at 4:10 PM Ville Voutilainen
<ville.voutilainen_at_[hidden]> wrote:
>
> I wonder what happened to the third strategy, which is to pass as the
> argument of existing emplace an object
> that will perform the function invocation in its conversion operator
> to the optional's element type, which then
> allows doing this without any library or language changes, and has
> field experience as a solution to this problem.


Do you mean something like the following?

GodBolt: https://godbolt.org/z/PfM1EKaWo

#include <optional>
#include <mutex>
#include <functional>

template<typename T>
class Monkey {

    std::function< T(void) > f;

public:

    template<typename F>
    Monkey(F &&arg)
    {
        f = std::forward<F>(arg);
    }

    operator T(void)
    {
        return f();
    }
};

std::mutex FuncThatReturnsMutex(void) { return std::mutex(); }

int main(void)
{
    std::optional<std::mutex> om;

    om.emplace( Monkey<std::mutex>(FuncThatReturnsMutex) );
}

Received on 2023-08-23 15:39:11