yaml-cpp
yaml-cpp copied to clipboard
Tutorial: How to encode custom types to YAML::Node's?
The tutorial shows how to decode custom types from YAML files. But I am not sure how to accomplish the reverse: How can we encode custom types back into YAML::Node's?
Here's an example from one of my projects:
// x,y,z position class encoded as [x, y, z] in YAML
namespace YAML
{
template<>
struct convert<Vector3>
{
static Node encode(const Vector3& rhs)
{
Node node;
node.push_back(rhs.x);
node.push_back(rhs.y);
node.push_back(rhs.z);
return node;
}
static bool decode(const Node& node, Vector3& rhs)
{
if (!node.IsSequence() || node.size() != 3)
return false;
rhs.x = node[0].as<int>();
rhs.y = node[1].as<int>();
rhs.z = node[2].as<int>();
return true;
}
};
}
Usage:
node["foo"] = Vector3(1, 2, 3);
Vector3 bar = node["bar"].as<Vector3>();