【发布时间】:2021-07-13 23:53:46
【问题描述】:
好的,我只是遇到了一个奇怪的问题。此示例需要 nlohmann json 库,但可能有人可以解释一下。
#include <nlohmann/json.hpp>
using JSON = nlohmann::json;
int main(int, char **) {
JSON json { JSON::object() };
json["foo"] = "bar";
}
相比:
#include <nlohmann/json.hpp>
using JSON = nlohmann::json;
int main(int, char **) {
JSON json = JSON::object();
json["foo"] = "bar";
}
第一个例子是这样做的:
terminate called after throwing an instance of 'nlohmann::detail::type_error'
what(): [json.exception.type_error.305] cannot use operator[] with a string argument with array
Aborted (core dumped)
第二个运行良好。
唯一的区别是json 的初始化语法。失败的使用{} 表示法,成功的使用= 表示法。我认为在这种情况下,这两种语法是完全等价的。显然不是。
我正在使用:
$ g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
有人能解释一下这两种初始化类型的区别吗?显然,它们不是 100% 可互换的。
【问题讨论】:
-
我猜,JSON 类有一个特殊的 ctor 重载,它采用 initializer_list。想想vector
v(5); 之间的区别。和矢量 v{5}; -
@IgorR。正确:nlohmann.github.io/json/api/basic_json/basic_json(构造函数 #5)。它创建一个数组。
-
不,这是故意的。
JSON json { JSON::object(), JSON::object(), JSON::object() };是“相同”的语法。单元素数组看起来很奇怪。这与写std::vector<int> x {3};是同一个“错误” -
@JosephLarson - 这不是现代问题。从第一个发布的标准开始,各种与重载相关的怪物都是可能的。试着弄清楚
std::string str("a", "b");做了什么。我们总是需要了解我们在做什么。 -
对这个问题的幽默看法:imgur.com/3wlxtI0
标签: c++