Really struggling to do this; it should be really simple, but I can't work out how. I've got it working for struct, but not for a class with private members. Following instructions from (https://github.com/nlohmann/json). I'm building this on Visual Studio 2019 and obtained the library from nuget, version 3.10.4.
The error is on the get line in main.cpp, where it says "no matching overloaded function call found.". There are two other errors listed;
Error (active) E0304 no instance of overloaded function "nlohmann::basic_json<ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType>::get [with ObjectType=std::map, ArrayType=std::vector, StringType=std::string, BooleanType=bool, NumberIntegerType=int64_t, NumberUnsignedType=uint64_t, NumberFloatType=double, AllocatorType=std::allocator, JSONSerializer=nlohmann::adl_serializer, BinaryType=std::vector<uint8_t, std::allocator<uint8_t>>]" matches the argument list Assignment4 C:\Users\allsoppj\source\repos\Assignment4\Assignment4\main.cpp 120
object type is: json
Error C2672 'nlohmann::basic_jsonstd::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>::get': no matching overloaded function found Assignment4 C:\Users\allsoppj\source\repos\Assignment4\Assignment4\main.cpp 120
Error C2893 Failed to specialize function template 'unknown-type nlohmann::basic_jsonstd::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>::get(void) noexcept() const' Assignment4 C:\Users\allsoppj\source\repos\Assignment4\Assignment4\main.cpp 120
Here's my address1.h
#include <nlohmann/json.hpp>
#include <string>
using json = nlohmann::json;
class address1 {
private:
std::string street;
int housenumber;
int postcode;
public:
address1(std::string street, int housenumber, int postcode);
NLOHMANN_DEFINE_TYPE_INTRUSIVE(address1, street, housenumber, postcode);
};
address1.cpp
#include "address1.h"
address1::address1(std::string street, int housenumber, int postcode) :street(street), housenumber(housenumber), postcode(postcode) {}
main.cpp
int main(int argc, const char** argv) {
address1 p1 = { "home",2,3 };
json j = p1;
auto p3 = j.get<address1>();
std::cout << std::setw(2) << j << std::endl;
}
CodePudding user response:
The problem is that your address1
type does not have a default constructor. From https://nlohmann.github.io/json/features/arbitrary_types/#basic-usage :
When using get<your_type>(), your_type MUST be DefaultConstructible. (There is a way to bypass this requirement described later.)
If I add address1() = default;
to your example, then it compiles no problem.
Ps. The "bypass described later" can be found here: https://nlohmann.github.io/json/features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-copyable-types