如何从nlohmann对象中提取底层数据类型信息?既然值作为原始数据类型存储在json中,为什么它不像下面这样给出a和b这样的输出呢?
对于有序的json,我在下面看到了typedef。
nlohmann::basic_json<nlohmann::ordered_map,std::vector, std::string, bool, std::int64_t, std::uint64_t, double>;因此,它存储的值的类型是明确的(?)。
int main()
{
json js;
js["key1"] = 1L;
js["key2"] = 0.111f;
auto a = 1L;
auto b = 0.111f;
decltype(js["key1"]) x = js["key1"];
decltype(js["key2"]) y = js["key2"];
cout<<typeid(a).name()<<endl;
cout<<typeid(b).name()<<endl;
cout<<typeid(x).name()<<endl;
cout<<typeid(y).name()<<endl;
}输出:
l
f
N8nlohmann10basic_jsonINS_11ordered_mapESt6vectorNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEblmdSaNS_14adl_serializerES2_IhSaIhEEEE
N8nlohmann10basic_jsonINS_11ordered_mapESt6vectorNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEblmdSaNS_14adl_serializerES2_IhSaIhEEEE发布于 2021-07-04 19:06:00
operator[]将返回一个用来保存该值的nlohmann::basic_json &类型。
您所看到的输出是nlohmann::basic_json模板类的损坏的专门化,该模板类已经为ordered定义了类型定义。
那是
nlohmann::basic_json<nlohmann::ordered_map,std::vector, std::string, bool, std::int64_t, std::uint64_t, double>;对应于
N8nlohmann10basic_jsonINS_11ordered_mapESt6vectorNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEblmdSaNS_14adl_serializerES2_IhSaIhEEEE因此,当您使用operator[]时,例如js["key1"],它会返回对该basic_json类型专门化的引用,因为这是存储在内部工作的方式。
但是,nlohmann还为stl类型提供了隐式转换,因此下面的示例将隐式地将operator[]返回的nlohmann::basic_json类型转换为(原始)数字类型
auto a = 1L;
auto b = 0.111f;
long x = js["key1"];
float y = js["key2"];
cout<<typeid(a).name()<<endl;
cout<<typeid(b).name()<<endl;
cout<<typeid(x).name()<<endl;
cout<<typeid(y).name()<<endl;隐式转换并不局限于将其转换为原始类型。例如,将原始long转换为int,并将float转换为double,也可以执行以下操作
js["key1"] = 1L;
js["key2"] = 0.111f;
int x = js["key1"];
double y = js["key2"];https://stackoverflow.com/questions/67136262
复制相似问题