Home > Net >  Unexpected implicit conversion from nlohmann::json to string
Unexpected implicit conversion from nlohmann::json to string

Time:12-21

While debugging an application I came up with the following example:

#include <nlohmann/json.hpp>

using nlohmann::json;
struct X {
    X(const std::string& s){}
};
int main() {
    X x("{}"_json); // why compiler allows this?
}

See at Godbolt

Could someone explain this? Is this a bug or an unexpected side effect of nlohmann/json library?


... and here is the second question:

As implicit to_string conversion is a documented feature, then is this a bug that this even simpler example fails at runtime?

#include <nlohmann/json.hpp>
using nlohmann::json;
int main() {
  std::string j = "{}"_json;  
}

terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_2::detail::type_error' what(): [json.exception.type_error.302] type must be string, but is object

CodePudding user response:

If you look up API docs here: https://github.com/nlohmann/json/search?q=operator string

You'll find that operator string_t() is a documented feature of the library to convert json_pointer to string_t. This conversion is considered when you call the ctor of X with an argument type that's not the listed argument type (const std::string&) and likely succeeds (to the extent that it can be compiled).

  • Related