Nlohmann Json "array" 和 "array_t" 之间的区别

Difference between Nlohmann Json "array" and "array_t"

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

array

Creates a JSON array value from a given initializer list. That is, given a list of values a, b, c, creates the JSON value [a, b, c]. If the initializer list is empty, the empty array [] is created.

示例,

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

array_t

To store objects in C++, a type is defined by the template parameters explained below.

  • Template Parameters
    • ArrayType container type to store arrays (e.g., std::vector or std::list)
    • AllocatorType allocator to use for arrays (e.g., std::allocator)

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

json

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<json> 的类型别名。
如果您在 basic_json.

上创建自己的 typedef,则可以覆盖传递给 basic_json 的类型