【问题标题】:Difference between Nlohmann Json "array" and "array_t"Nlohmann Json“array”和“array_t”之间的区别
【发布时间】:2020-10-20 11:21:12
【问题描述】:

nlohmann array_t 与 Nlohmann json array 有何不同? array_t 是如何实际使用的?每个文档如下。

array

从给定的初始化列表创建一个 JSON 数组值。也就是说,给定值 a、b、c 的列表,创建 JSON 值 [a, b, c]。如果初始化列表为空,则创建空数组 []。

例子,

nlohmann::json j_nonempty_init_list = json::array({1, 2, 3, 4});
std::cout << j_nonempty_init_list;
// [1,2,3,4]

array_t

为了在 C++ 中存储对象,类型由下面解释的模板参数定义。

  • 模板参数
    • ArrayType 用于存储数组的容器类型(例如 std::vector 或 std::list)
    • AllocatorType 用于数组的分配器(例如,std::allocator)

【问题讨论】:

    标签: c++ nlohmann-json


    【解决方案1】:

    json::array 是一个静态函数,它将初始化列表转换为内部类型为 value_t::arrayjson 值。

    array_t定义如下:

    using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
    

    其中ArrayTypebasic_json 的模板模板参数:

    template<template<typename U, typename V, typename... Args> class ObjectType =
             std::map,
             template<typename U, typename... Args> class ArrayType = std::vector,
             class StringType = std::string, class BooleanType = bool,
             class NumberIntegerType = std::int64_t,
             class NumberUnsignedType = std::uint64_t,
             class NumberFloatType = double,
             template<typename U> class AllocatorType = std::allocator,
             template<typename T, typename SFINAE = void> class JSONSerializer =
             adl_serializer,
             class BinaryType = std::vector<std::uint8_t>>
    class basic_json;
    

    最后nlohmann::json 只是默认实例化:

    using json = basic_json<>;
    

    所以,json::array_t 最终是std::vector&lt;json&gt; 的类型别名。
    如果您在 basic_json 上创建自己的 typedef,则可以覆盖传递给 basic_json 的类型。

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 2012-05-21
      • 2019-01-28
      • 2016-05-12
      • 2012-12-23
      • 2021-06-10
      • 2016-05-03
      • 1970-01-01
      相关资源
      最近更新 更多