c++ - E0349:在使用 nlohmann-json 使用 JSON 时,没有运算符“=”匹配这些操作数
问题描述
我nlohmann-json
在 Visual Studio 上的 C++ 项目中使用,我发现了一个错误
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]);
}
}
推荐阅读
- android - “npm start”和“react-native run-android”部署有什么区别?
- android - 为 Android 编译 PDFium 的正确选项是什么?
- azure - Azure blob 存储:从浏览器上传时检查 blob mime 类型
- javascript - 如何使用javascript在html中显示文本文件中的文本
- javascript - React 扩展组件渲染函数调用
- php - 使用 PHP 的动态 CSS
- node.js - 如何附加文档和更新密钥
- karate - 如何从项目 jar 运行空手道测试?
- sql-server - SSIS“执行报告”错误-“报告无效”-在 SSMS 中间歇性出现-原因?
- amp-html - 是否可以在不包含 v0.js 脚本的情况下创建 AMP 页面?