json: `if_contains` currently returns `value*`, but it'd be better if it returned `optional`
Currently, json::object provides if_contains that returns a json::value* (or json::value const*). This is a useful API, definitely more ergonomic than having to call find() and check against end().
However, it could be more ergonomic still. boost::optional actually supports references, and boost::optional<value&> is a much more appropriate type here than value*. For simple uses, they’re the same:
if (auto value = obj.if_contains(key)) {
use(*value);
}
But returning optional allows you to chain further operations and more conveniently access that underlying value. Like, say:
int val = obj.if_contains(key)
.map([](json::value const& v){ return v.to_number<int>(); })
.value_or(-1);
optional enables this approach, whereas with pointers you’d have to do something like:
int val = [&]{
auto p = obj.if_contains(key);
return p ? p->to_number<int>() : -1;
}();
This pretty quickly gets more and more clunky. And then here’s a bunch more reasons to prefer optional<value&> here.
In short, even if you don’t care much for the continuation style, optional<value&> supports all the existing valid uses of value* that exist today, doesn’t support any of the existing invalid uses (like delete-ing the pointer, indexing the pointer, incrementing the pointer, …), and supports more useful operations that do regularly come up (like map, and_then, value_or, …)
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 16 (14 by maintainers)
#941 adds accessor functions that return
system::result<T&>. I decided against changing existing functions, because I considered that change to be too disruptive. So, closing as “not planned”.