Open weepy opened 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.
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.
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)
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.
I added the following to json11.hpp
It makes using json11 much more convenient as the compiler will auto cast your variables for you, eg:
int id = myJson["id"];