Writing a mapping

struct highest_point {
    std::string continent;
    std::string name;
    std::string country;
};

x::yaml::newnode highest_point_to_yaml(const highest_point &hp)
{
    return x::yaml::newmapping::create
        ([hp]
        (x::yaml::newmapping &info)
        {
            std::list<std::pair<x::yaml::newnode, x::yaml::newnode>> list;

            list.push_back(
                std::make_pair(x::yaml::newscalarnode::create("continent"),
                               x::yaml::newscalarnode::create(hp.continent)));
            list.push_back(
                std::make_pair(x::yaml::newscalarnode::create("name"),
                               x::yaml::newscalarnode::create(hp.name)));
            list.push_back(
                std::make_pair(x::yaml::newscalarnode::create("country"),
                               x::yaml::newscalarnode::create(hp.country)));
            info(list.begin(), list.end());
        });
}

x::yaml::newmapping::create() constructs a x::yaml::newnode that writes a mapping in a YAML document.

create() takes a lambda or a functor for a parameter, which gets called to define the mapping. The lambda functor takes one parameter, an instance of x::yaml::newmapping that's passed by reference, with the following members:

anchor

An optional anchor for an alias reference to this node.

tag

An optional YAML tag handle for this mapping node. This handle must be included in the x::yaml::newdocumentnode's tags map.

style

One of YAML_ANY_MAPPING_STYLE (default), YAML_BLOCK_MAPPING_STYLE, or YAML_FLOW_MAPPING_STYLE.

implicit

Defaulting to true this specifies that this node's YAML tag is optional.

The lambda/functor can modify these members from their default values before invoking the object's () operator, which takes two parameters, a beginning and an ending iterator. The above example creates a temporary list containing std::pairs x::yaml::newnodes but the iterators can be of any type that define an input sequence over a std::pair of x::yaml::newnodes or x::yaml::const_newnode; this input sequence defines the YAML mapping that gets written to the new document.

Note

Do not proceed to the next section until it's understood why, in the example above, the lambda captures the record by value.

Answer: the above example constructs an object that calls the lambda to write the YAML document. The lambda does not get invoked by highest_point_to_yaml(), it only constructs the object with the lambda, which gets invoked when the document actually gets written.

The record gets captured by value, so that at the time that the YAML document gets written, the record is in scope, and is valid. If it can be assured that the parameter to highest_point_to_yaml() will remain in scope, then it can be captured by reference, but in practice the safe thing to do is to capture it by value.