dropbox / json11

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

in json11.cpp line 161 , why use static_cast, what if a json object is a runtime parsed object #118

Closed 678uhb closed 6 years ago

678uhb commented 6 years ago

in json11.cpp line 161 , why use static_cast, what if a json object is a runtime parsed object

 // Comparisons
    bool equals(const JsonValue * other) const override {
        return m_value == static_cast<const Value<tag, T> *>(other)->m_value;
    }
    bool less(const JsonValue * other) const override {
        return m_value < static_cast<const Value<tag, T> *>(other)->m_value;
    }
artwyman commented 6 years ago

The value in m_value may be parsed at runtime, but that doesn't matter here. This is dealing with JsonValue, which is a private template used as an internal implementation detail of Json, which supports only a known, fixed number of value types, identified by the type tag. Note that by the time we reach a call to this function (in operator== below) we've already checked the type tag and know the two values are of the same type. We always consider values of different types to be non-equal. This function only handles values of the same type, and thus simply uses static_cast to cast the argument to the correct sublcass and access m_value as the correct type.