
Examples
Suppose we have a class hierarchy with members that need to be instantiated from config files or some other dynamic data.
struct MyBase
{};
struct MyDerived : public MyBase
{
struct Config
{
int x, y;
};
MyDerived(const Config &) {}
};
This library helps create objects in the hierarchy from json or yaml data.
After registering tags with derived types (see below) creating instances is as easy as this for yaml:
std::string yaml_data = R"(
!mytag
x: 1
y: 2
)";
auto obj = YAML::Load(yaml_data).as<std::unique_ptr<MyBase>>();
Similarly for json:
std::string json_data = R"(
{"mytag": {"x": 1, "y": 2}}
)";
auto obj = nlohmann::json::parse(json_data).get<std::unique_ptr<MyBase>>();
It also works with STL types. For example:
std::string json_data = R"(
{
"key1": {"mytag": {"x": 1, "y": 2}},
"key2": {"mytag": {"x": 3, "y": 4}}
}
)";
auto obj = nlohmann::json::parse(json_data).get<std::map<std::string, std::unique_ptr<MyBase>>>();
Register yaml converter
Yaml conversion uses yaml-cpp
.
template<>
{
static bool decode(const YAML::Node & yaml, MyDerived::Config & obj)
{
obj.x = yaml["x"].as<int>();
obj.y = yaml["y"].as<int>();
return true;
}
};
#define EZ_YAML_REGISTER(Base, tag, Derived,...)
Register a conversion method with the global yaml factory.
#define EZ_YAML_DEFINE(Base)
Define a global yaml factory for a base class.
Yaml factory forward declarations.
#define EZ_YAML_DECLARE(Base)
Declare a global yaml factory for a base class.
Register json converter
Json conversion uses nlohmann_json
.
void from_json(const nlohmann::json & j, MyDerived::Config & p)
{
p.x = j.at("x").get<int>();
p.y = j.at("y").get<int>();
}
#define EZ_JSON_REGISTER(Base, tag, Derived,...)
Register a tagged conversion with a json factory.
#define EZ_JSON_DEFINE(Base)
Define a global json factory for a base class.
Json factory forward declarations.
#define EZ_JSON_DECLARE(Base)
Declare a json factory for a base class.
TODOs
- Extra yaml types decode
- Extra yaml types encode