dropbox / json11

A tiny JSON library for C++11.
MIT License
2.55k stars 613 forks source link

`bool operator !` overloading #50

Closed ttti07 closed 8 years ago

ttti07 commented 8 years ago

How about adding an logical operator bool Json::operator! () const { return is_null(); } ? I'd like to use syntax like this:

json11::Json obj = json11::Json::parse(myJsonStr, errorStr);
if (!obj["MyKey"])
    return false;
artwyman commented 8 years ago

@j4cbo might remember best the logic behind deciding not to do that (or the similar operator bool approach) when this library was first developed. My thought would be that it would be a pattern easy to misunderstand depending on your expectations of JSON. E.g. it's not obvious if it's checking only for null, or also for a boolean value (it's a bit awkward to have a boolean operation which has a different meaning from bool_value()), or integer values which C++ programmers would expect to be true if non-zero, or other values which would be defined as "falsy" by JavaScript or Python, like empty strings, empty arrays, etc. Making any test explicit rules out any confusion about what exactly it should mean.

j4cbo commented 8 years ago

Yep, that's exactly it. There are a bunch of possible meanings of an implicit boolean cast. Making the cast check only for null would be one option, but Javascript also has its own convoluted truthiness semantics which are kinda convoluted, and which users might expect. Any possible meaning of an implicit cast might be surprising to someone, so we decided to require that the intent be written out explicitly.

ttti07 commented 8 years ago

Oh, I didn't think of that about... Your decision seems reasonable, and I agree with that philosophy too. Keep the most appropriate way of C++. Thanks for your explanation.