yaml-cpp
yaml-cpp copied to clipboard
Use structure binding for YAML::Node
It is possible to use structure binding when we want to iterate through YAML::Node?
for(const auto& n : node) {
auto a = n.first.as<std::string>();
auto b = n.second;
// Some code bellow
}
I wish to get something like that:
for(auto [a,b] : node)
{
// Some code bellow
}
Is that possible and how can I use structure binding with YAML::Node? The reason for the change is more readable code. This type of code is used in multiple places and structure binding is a good way to implement a prettier solution. If this is possible, how can I use that, and maybe the example can be added in documentation or in the test.
YAML allows non-string keys. I'm afraid the specific syntax you ask for is unachievable for that reason.
for(auto& [a,b] : node) { }
Is valid code. as value returned is class that inherit std::pair<YAML::Node, YAML::Node> and YAML::Node.
If you want string key then you can add custom class that extract string key from node:
struct Node { void operator++(){} };
struct NodeIterValue : std::pair<Node, Node>, Node
{
};
struct KeyValue
{
KeyValue(std::pair<Node, Node> p) : key{p.first}, value{p.second} { }
Node key; //you could get `p.first.as<X>` to init this
Node value;
};
int main()
{
NodeIterValue i[4] = {};
for (Node& d : i){ ++d; }
for (auto& [a, b] : i) { ++a; }
for (KeyValue k : i) { ++k.value; }
}