Skip to content
This repository has been archived by the owner on Mar 26, 2020. It is now read-only.

auto casting #130

Open
weepy opened this issue Nov 16, 2018 · 4 comments
Open

auto casting #130

weepy opened this issue Nov 16, 2018 · 4 comments

Comments

@weepy
Copy link

weepy commented Nov 16, 2018

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
Copy link

daid commented Nov 20, 2018

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
Copy link
Author

weepy commented Nov 20, 2018

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
Copy link

daid commented Nov 20, 2018

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
Copy link
Contributor

j4cbo commented Nov 25, 2018

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants