12#include <nlohmann/json.hpp>
29#define EZ_JSON_DEFINE(Base) \
30 EZ_FACTORY_DEFINE(Base, const nlohmann::json &); \
31 template std::unique_ptr<Base> ezconfig::json::Create<Base>(const nlohmann::json &); \
32 template struct nlohmann::adl_serializer<std::shared_ptr<Base>>; \
33 template struct nlohmann::adl_serializer<std::unique_ptr<Base>>
53#define EZ_JSON_REGISTER(Base, tag, Derived, ...) \
54 EZ_STATIC_INVOKE(&ezconfig::json::Add<Base, Derived __VA_OPT__(, ) __VA_ARGS__>, tag)
56namespace ezconfig::json {
61 {j.get<T>()} -> std::convertible_to<T>;
78template<
typename Base,
typename Derived,
typename Intermediate = Derived>
81 && std::is_constructible_v<Derived, Intermediate &&>)
82void Add(
const std::string & tag)
84 auto creator = [](
const nlohmann::json & json) {
return std::make_unique<Derived>(json.get<Intermediate>()); };
85 EZ_FACTORY_INSTANCE(Base,
const nlohmann::json &).add(tag, std::move(creator));
88template<
typename Base>
89std::unique_ptr<Base>
Create(
const nlohmann::json & json)
91 if (!json.is_object() || json.size() != 1) {
92 throw std::logic_error(
"Expected dictionary of size 1 of format {tag: object}");
94 return EZ_FACTORY_INSTANCE(Base,
const nlohmann::json &).create(json.begin().key(), json.begin().value());
99template<ezconfig::json::Constructible Base>
100void nlohmann::adl_serializer<std::shared_ptr<Base>>::from_json(
const json & j, std::shared_ptr<Base> & ptr)
102 ptr = ::ezconfig::json::Create<Base>(j);
105template<ezconfig::json::Constructible Base>
106void nlohmann::adl_serializer<std::unique_ptr<Base>>::from_json(
const json & j, std::unique_ptr<Base> & ptr)
108 ptr = ::ezconfig::json::Create<Base>(j);
std::unique_ptr< Base > Create(const nlohmann::json &json)
Create an object using the factory.
void Add(const std::string &tag)
Add a factory method.
Json factory forward declarations.