C++17 联合体

两种风格的json如何解析更方便?------联合体哈希

(github有现成的json解析库;此文仅用于C++高级语法的学习)

json 复制代码
{
  "0x1": "a",
  "0x2": "b",
  "0x3": "c",
  "0x4": {
    "A": "d",
    "B": "e"
  },
  "0x5": {
    "A": "f",
    "B": "g",
    "C": "h"
  },
  "0x6": "i"
}

1. using ConfigNode= std::unordered_map<std::string, std::string>;

cpp 复制代码
// 等价于:
typedef std::unordered_map<std::string, std::string> ConfigNode;  // 旧式写法

2. using ConfigValue = std::variant<std::string, ConfigNode>;

定义另一个类型别名 ConfigValue,它代表 std::variant<std::string, SubConfig>

  • std::variant 是 C++17 引入的类型安全的联合体 (union)。它可以存储给定类型列表中的任意一种类型。
  • 这里 ConfigValue 的对象要么存一个 std::string,要么存一个 SubConfig(即 unordered_map)。不能同时存两者。

3. 为什么这样写?

在配置系统中,一个键对应的值可能有两种情况:

  • 直接是简单字符串(如 "a"
  • 或者是包含多个子键值对的"子映射"(如 {"A":"d", "B":"e"}

std::variant 完美表达了这种"或"的关系,而 using 让代码意图更清晰。

4.如果json有多层嵌套

cpp 复制代码
struct ConfigNode;
using ConfigValue = std::variant<std::string, std::unordered_map<std::string, std::shared_ptr<ConfigNode>>>;

struct ConfigNode {
    ConfigValue value;
};
相关推荐
clint4563 天前
C++进阶(1)——前景提要
c++
夜悊3 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴3 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0013 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
LDR0064 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术4 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园4 天前
C++20 Modules 模块详解
java·开发语言·spring
swordbob4 天前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
源分享4 天前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Luminous.4 天前
C语言--day30
c语言·开发语言