Chciałem zrobić serializacje struktur które dziedziczą po sobie struct personEXT :public person
Klasa która dziedziczy wykorzystuje funkcje serializacji to_json/from_json przodka
Działa , ale czy to jest zgodne ze sztuką ?
Czy można to zrobić bez operatora personEXT& operator=(person const& copy)
?
#include <iostream>
#include <string>
#include <spdlog/spdlog.h>
#include <nlohmann/json.hpp>
// for convenience
using json = nlohmann::json;
namespace ns {
// a simple struct to model a person
struct person {
std::string name;
std::string address;
int age;
};
void to_json(json& j, const person& p) {
j = json{{"name", p.name},
{"address", p.address},
{"age", p.age}};
}
void from_json(const json& j, person& p) {
j.at("name").get_to(p.name);
j.at("address").get_to(p.address);
j.at("age").get_to(p.age);
}
struct personEXT :public person
{
std::string surname;
personEXT& operator=(person const& copy)
{
person::operator=(copy); //
return *this;
};
};
void to_json(json& j, const personEXT& p) {
j = static_cast<person>(p);
j["surname"]=p.surname;
}
void from_json(const json& j, personEXT& p) {
p = j.get<person>();
j.at("surname").get_to(p.surname);
}
}
int main()
{
ns::personEXT pEXT{"nameEXT", "adressEXT",99,"surname"};
json jEXT =pEXT;
fmt::print("\n\n{}",jEXT.dump(2));
ns::personEXT pETX_new = jEXT.get<ns::personEXT>();
json jEXT_new =pETX_new;
fmt::print("\n\n{}",jEXT_new.dump(2));
}