dropbox / json11

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

auto casting #130

Open weepy opened 6 years ago

weepy commented 6 years ago

I added the following to json11.hpp

 /// @weepy additions
        operator long() {
            return (long) int_value();
        }

        operator int() {
            return int_value();
        }
        operator float() {
            return (float) number_value();
        }
        operator double() {
            return (double) number_value();
        }
        operator std::string() {
            return string_value();
        }
        operator bool() {
            return bool_value();
        }

        operator object() {
            return object_items();
        }

        operator array() {
            return array_items();
        }

It makes using json11 much more convenient as the compiler will auto cast your variables for you, eg:
int id = myJson["id"];

daid commented 6 years ago

You want to make those const:

operator int() const {
            return int_value();
}

Or you compiler might decide some really strange casts in some cases where there are temporaries.

Next, I recommend against it, implicit casts to integer types (including bool) from objects is very easy to go wrong.

weepy commented 6 years ago

Not had a problem so far - but thanks for that !

What do you mean by " implicit casts to integer types (including bool) from objects is very easy to go wrong." ? I've found that if you try to read the wrong type, you'll just get a zero.

daid commented 6 years ago

Well, compilers can decide to implicitly cast without you expecting it.

I think this example works unexpectedly, as both Foo instances are cast to bool in the if(), and then the compare is true.

class Foo
{
public:
    Foo(int n) : value(n) {}

    operator bool() const
    {
        return value != 0;
    }
private:
    int value;
};

Foo bar()
{
    return Foo(1);
}

void test()
{
    if (bar() == Foo(2)) { printf("True!\n"); }
}

You can have the same thing if you compare objects that are incompatible for comparison, or if the comparison operator isn't defined const while the casts are (at this example also includes a temporary)

j4cbo commented 6 years ago

I would definitely recommend defining the conversion functions as explicit (https://en.cppreference.com/w/cpp/language/cast_operator) to reduce the risk of the unexpected conversions mentioned above. Even so, I'm not sure this is something we'd want to merge in upstream - better to keep "down-casts" explicit.