boostorg / json

A C++11 library for parsing and serializing JSON to and from a DOM container in memory.
https://boost.org/libs/json
Boost Software License 1.0
432 stars 94 forks source link

Confusion regarding result_for #961

Closed panic-sell closed 9 months ago

panic-sell commented 9 months ago

I'm having trouble understanding the purpose of result_for.

Per docs at https://www.boost.org/doc/libs/1_83_0/libs/json/doc/html/json/ref/boost__json__result_for.html: The purpose of this trait is to let users provide non-throwing conversions for their types without creating a physical dependency on Boost.Json. How can someone not create a physical dependency on Boost.Json if they are already using this library?

If result_for<T, value>::type is identical to result<T>, the former is unnecessary extra typing. If I'm working on a project that uses Boost.Json facilities to perform JSON conversions (i.e. my project depends on Boost.Json), it seems to me there's no reason to prefer result_for over result.

Maybe I'm just missing something really obvious.

pdimov commented 9 months ago

You can forward-declare result_for. See for example how it's done in Variant2: https://github.com/boostorg/variant2/blob/9e4234bfd5688c0272b641954ab2f23f8ce9c613/include/boost/variant2/variant.hpp#L2430-L2530

panic-sell commented 9 months ago

Thanks. IIUC, by forward declaring all Boost.Json names and only implementing tag_invoke() in terms of those forward declarations, we can avoid making our custom types depend on Boost.Json

That said, I notice examples in https://www.boost.org/doc/libs/1_83_0/libs/json/doc/html/json/conversion/non_throwing_conversions.html use result_for (despite depending on Boost.Json per calls to jv.get_array()). Is the recommendation to prefer result_for over result even when code does depend on Boost.Json? If so, why?

pdimov commented 9 months ago

The same example does use result directly inside the function; result_for in the signature is probably only used to match the declaration of tag_invoke given above.

I can't think of any reason to prefer result_for if you don't mind including JSON (or System) headers.

grisumbras commented 9 months ago

Yes, there's absolutely no reason to prefer result_for over result If you're including JSON headers. As @pdimov suggested, the linked example uses result_for in the return type to match the signature, in order to be less confusing for the user.

panic-sell commented 9 months ago

Awesome, thanks for the explanation.