E0349:no 运算符“=”在使用 JSON 使用 nlohmann-json 时匹配这些操作数
E0349:no operator "=" matches these operands when using JSON using nlohmann-json
我在 Visual Studio 上的 C++ 项目上使用 nlohmann-json
,我发现了一个错误
E0349:no operator "=" matches these operands
在下面的代码中:
#include <nlohmann/json.hpp>
using json = nlohmann::json;
void myFunc(unsigned int** arr) {
json j;
j["myArr"] = arr;//E0349:no operator "=" matches these operands
}
怎么了?
另一方面,当我尝试以下方法时,它起作用了。
void myFunc(unsigned int** arr) {
json j;
j["myArr"] = {1,2,3};// no error
}
我猜这是数据类型问题。
如有任何信息,我将不胜感激。
nlohmann json 仅支持从 C++ 标准库容器创建数组。不可能从指针创建数组,因为它没有关于数组大小的信息。
如果你有 c++20,那么你可以使用 std::span
将指针(和大小)转换为容器:
#include <nlohmann/json.hpp>
#include <span>
using json = nlohmann::json;
void myFunc(unsigned int* arr, size_t size) {
json j;
j["myArr"] = std::span(arr, size);
}
如果你没有 c++20,你将不得不自己实现 std::span
或者将你的数组复制到类似 std::vector
的东西中(或者只使用 std::vector
开始使用而不是原始数组)。
或者手动构建数组(这里你仍然需要一个大小):
void myFunc(unsigned int* arr, size_t size) {
json j;
auto& myArr = j["myArr"];
for (size_t i = 0; i < size; i++)
{
myArr.push_back(arr[i]);
}
}
我在 Visual Studio 上的 C++ 项目上使用 nlohmann-json
,我发现了一个错误
E0349:no operator "=" matches these operands
在下面的代码中:
#include <nlohmann/json.hpp>
using json = nlohmann::json;
void myFunc(unsigned int** arr) {
json j;
j["myArr"] = arr;//E0349:no operator "=" matches these operands
}
怎么了?
另一方面,当我尝试以下方法时,它起作用了。
void myFunc(unsigned int** arr) {
json j;
j["myArr"] = {1,2,3};// no error
}
我猜这是数据类型问题。
如有任何信息,我将不胜感激。
nlohmann json 仅支持从 C++ 标准库容器创建数组。不可能从指针创建数组,因为它没有关于数组大小的信息。
如果你有 c++20,那么你可以使用 std::span
将指针(和大小)转换为容器:
#include <nlohmann/json.hpp>
#include <span>
using json = nlohmann::json;
void myFunc(unsigned int* arr, size_t size) {
json j;
j["myArr"] = std::span(arr, size);
}
如果你没有 c++20,你将不得不自己实现 std::span
或者将你的数组复制到类似 std::vector
的东西中(或者只使用 std::vector
开始使用而不是原始数组)。
或者手动构建数组(这里你仍然需要一个大小):
void myFunc(unsigned int* arr, size_t size) {
json j;
auto& myArr = j["myArr"];
for (size_t i = 0; i < size; i++)
{
myArr.push_back(arr[i]);
}
}