c++ - C++ Nlohman::json 第三方支持不编译
问题描述
我正在使用 nlohmann::json 来(反)序列化 JSON 中的一些 C++ 对象。我还不明白如何设置代码以使用第三方库 (SoapySDR)。在此示例中,我的代码位于全局命名空间中,而 SoapySDR 代码位于其自己的命名空间中。通过这个简化的示例,我得到了大量的编译错误:
#include "json.hpp"
using nlohmann::json;
namespace SoapySDR
{
class Range
{
public:
double minimum(void) const;
double maximum(void) const;
double step(void) const;
private:
double _min, _max, _step;
};
class ArgInfo
{
public:
Range range;
};
}; // namespace SoapySDR
void to_json(json &j, const SoapySDR::Range &r)
{
j += {"min",r.minimum()};
j += {"max",r.maximum()};
j += {"step",r.step()};
}
void from_json(const json &j, SoapySDR::Range &r)
{
// r = SoapySDR::Range(j.at("min"), j.at("max"), j.at("step"));
}
void to_json(json &j, const SoapySDR::ArgInfo &ai)
{
j = json{{"range", ai.range}};
}
void from_json(const json &j, SoapySDR::ArgInfo &ai)
{
j.at("range").get_to(ai.range);
}
这些是错误消息,不包括有关尝试扣除的所有额外信息:
bob.cpp:41:31: error: no matching function for call to ‘nlohmann::basic_json<>::basic_json(<brace-enclosed initializer list>)’
bob.cpp:41:31: note: couldn't deduce template parameter ‘JsonRef’
bob.cpp:41:31: note: couldn't deduce template parameter ‘BasicJsonType’
bob.cpp:41:31: note: couldn't deduce template parameter ‘CompatibleType’
j = json{{"range", ai.range}};
bob.cpp:46:32: error: no matching function for call to ‘nlohmann::basic_json<>::get_to(SoapySDR::Range&) const’
j.at("range").get_to(ai.range);
json.hpp:19588:28: error: no type named ‘type’ in ‘struct std::enable_if<false, int>’
int > = 0 >
json.hpp:19613:11: note: template argument deduction/substitution failed:
bob.cpp:46:32: note: mismatched types ‘T [N]’ and ‘SoapySDR::Range’
j.at("range").get_to(ai.range);
解决方案
数据类型的to_json
andfrom_json
重载需要在类型的命名空间中,以便库找到它们:
namespace SoapySDR {
void to_json(json &j, const SoapySDR::Range &r)
{
j += {"min",r.minimum()};
j += {"max",r.maximum()};
j += {"step",r.step()};
}
/* ... */
}
之后,您的代码将编译:https ://godbolt.org/z/5cafYx
推荐阅读
- python - 在一组补丁周围画一个周长?
- javascript - 在 webpack 和 bootstrap 4 中包含自定义字体类型不起作用
- python - 添加具有位于某些其他列中任何位置的条件值的列
- html - 我页面右侧的奇怪空白区域 - CSS
- ios - 如何使用 MTLSamplerState 而不是在我的片段着色器代码中声明采样器?
- parallel-processing - 我无法让 pool.map 或 pool.starmap 以我认为应该的方式工作
- c - PIC16F887 接收到错误的 UART 数据
- python - 蛇形扩展没有输入文件
- c# - 为什么即使生成的机器代码几乎相同,C# 的速度却是 C++ 的两倍?
- sympy - 计算具有不同结束索引的产品