yaml-cpp icon indicating copy to clipboard operation
yaml-cpp copied to clipboard

Use structure binding for YAML::Node

Open nejcgalof opened this issue 4 years ago • 2 comments

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.

nejcgalof avatar Nov 08 '21 13:11 nejcgalof

YAML allows non-string keys. I'm afraid the specific syntax you ask for is unachievable for that reason.

KitsuneRal avatar Dec 31 '21 04:12 KitsuneRal

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; }
}

Yankes avatar Mar 29 '22 19:03 Yankes