问题描述
我正在使用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
和from_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