Tutorial · jbeder/yaml | 您所在的位置:网站首页 › yamlcpp › Tutorial · jbeder/yaml |
Introduction
A typical example, loading a configuration file, might look like this: YAML::Node config = YAML::LoadFile("config.yaml"); if (config["lastLogin"]) { std::cout YAML::Node node = YAML::Load("{pi: 3.14159, [0, 1]: integers}"); // this needs the conversion from Node to double double pi = node["pi"].as(); // this needs the conversion from double to Node node["e"] = 2.71828; // this needs the conversion from Node to std::vector (*not* the other way around!) std::vector v; v.push_back(0); v.push_back(1); std::string str = node[v].as();To use yaml-cpp with your own data types, you need to specialize the YAML::convert template class. For example, suppose you had a simple Vec3 class: struct Vec3 { double x, y, z; /* etc - make sure you have overloaded operator== */ };You could write namespace YAML { template struct convert { static Node encode(const Vec3& 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, Vec3& rhs) { if(!node.IsSequence() || node.size() != 3) { return false; } rhs.x = node[0].as(); rhs.y = node[1].as(); rhs.z = node[2].as(); return true; } }; }Then you could use Vec3 wherever you could use any other type: YAML::Node node = YAML::Load("start: [1, 3, 0]"); Vec3 v = node["start"].as(); node["end"] = Vec3(2, -1, 0); |
CopyRight 2018-2019 实验室设备网 版权所有 |