You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

nlohmann-json在GCC与MSVC(C++14)下输出不一致问题咨询

nlohmann-json在GCC与MSVC下的初始化列表解析差异问题解析

问题情况

  • 触发代码:output["test"] = {nlohmann::json::array()};
  • GCC(C++14标准编译)输出:{"test":[[]]}
  • MSVC(C++14标准编译)输出:{"test":[]}
  • 移除外层大括号后(output["test"] = nlohmann::json::array();),两款编译器输出一致为{"test":[]}

原因说明

这既不是nlohmann-json库的bug,也不是某款编译器的bug,核心是C++14标准对初始化列表重载解析的规则存在模糊地带,导致两款编译器选择了不同的赋值重载分支:

  • nlohmann::json::array()本身会返回一个空的JSON数组对象(类型为nlohmann::json)。
  • 当使用{nlohmann::json::array()}作为赋值右值时:
    • MSVC将{...}解析为单个nlohmann::json对象的初始化,匹配直接接受json对象的赋值重载,最终等价于直接赋值空数组,输出[]。
    • GCC则将{...}解析为std::initializer_list<nlohmann::json>,匹配接受初始化列表的赋值重载,相当于创建了一个包含空数组的新数组,因此输出嵌套数组[[]]。
  • 这种分歧在C17标准中被修复——标准明确了这类场景下的重载优先级,升级到C17后两款编译器的行为会完全一致。

解决办法

  • 最直接的方式:移除外层大括号,使用output["test"] = nlohmann::json::array();,明确指定赋值单个空数组对象。
  • 若要保留初始化列表写法:显式指定类型,写成output["test"] = nlohmann::json{nlohmann::json::array()};,强制编译器将大括号内容解析为单个json对象。

内容的提问来源于stack exchange,提问作者Constantin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:15:32