json icon indicating copy to clipboard operation
json copied to clipboard

Add a nonthrowing overload for value_to

Open pdimov opened this issue 1 year ago • 1 comments

Implementing value_to for variant (for one possible representation) involves repeatedly trying value_to for each alternative. Since value_to reports failures via exceptions, this will be slow. It would be better if value_to had a noexcept overload that could be used for this purpose.

There's no perfect option here, because returning result<T> would impose a dependency on System, and we want people to be able to add JSON support without a dependency. The other alternative

bool value_to( value const& jv, T& t, error_code& ec );

would require T to be default-constructible, but this may be good enough, as the "traditional" value_to can be used for other types.

A default implementation for this overload would be

bool value_to( value const& jv, T& t, error_code& ec )
{
    try
    {
        t = value_to( jv );
        return true;
    }
    catch( system_error const& x )
    {
        ec = x.code();
    }
    catch( ... )
    {
        ec = ...;
    }

    return false;
}

but "basic" types should have proper nonthrowing overloads.

pdimov avatar Aug 03 '22 08:08 pdimov

See also https://github.com/boostorg/json/issues/667.

pdimov avatar Aug 07 '22 08:08 pdimov