yaml-cpp
yaml-cpp copied to clipboard
Need explanation / improve tutorial
I just started using yaml-cpp and I did navigation from key like: "my.magic.str.value" to access nested values in YAML files.
I did this with code:
YAML::Node node = _root;
for(const auto& element : path)
{
node = node[element];
if(!node)
{
return node;
}
}
return node;
So thanks to that I could navigate through tree.
It works fine for first execution then it stops as we modify _root ...
I found this question also: https://stackoverflow.com/questions/43597237/yaml-cpp-modifies-underlying-container-even-for-const-nodes
It would be nice to explain this in tutorial or forbid it somehow. Solution is to use recursion. E.g.
static YAML::Node goDeep(YAML::Node parent, unsigned level, const std::vector<std::string>& levels)
{
if(level == levels.size())
{
return parent;
}
if(!parent)
{
return parent;
}
return goDeep(parent[levels.at(level)], level + 1, levels);
}
YAML::Node ConfigValue::find(const std::string& key) const
{
const auto levels = gcpp::string::split(key, "."s);
return goDeep(*_storage, 0, levels);
}
I face the same issue in implementing the same behavior. It renders this library useless, especially since there are no compiler warnings despite marking my class member function const. A contract is broken.
FYI Ive hit the same issue, I had to wrap YAML::Node in my own object to control for this behavior
I have the same issue. The assignment semantics for Node makes no sense. Even if it acts as a pointer, accessing a copy should not modify original object. I guess I'll have to use libfyaml...
Please, either open Wiki for editing or update tutorial. Thanks!