how to set yaml-cpp node style?

2019-05-10 07:53发布

问题:

I have a vector3 class.

class vector3
{
    float x, y, z;
}

node["x"] = vector3.x;
node["y"] = vector3.y;
node["z"] = vector3.z;

The result is

x: 0
y: 0
z: 0

I want the result to be:

{x: 0, y: 0, z: 0}

If use the old API, I can use YAML::Flow to set the style:

YAML::Emitter emitter;
out << YAML::Flow  << YAML::BeginMap << YAML::Key << "x" << YAML::Value << x << YAML::EndMap

Using the new API, how can I set the style?

I asked this question on a yaml-cpp project issue page:

https://code.google.com/p/yaml-cpp/issues/detail?id=186

I got the answer:

You can still use the emitter and set the flow style:

YAML::Emitter emitter;
emitter << YAML::Flow << node;

but the vector3 is part of the object. I specialize the YAML::convert<> template class

template<>
struct convert<vector3>
{
    static Node encode(const vector3 & rhs)
    {
        Node node = YAML::Load("{}");
        node["x"] = rhs.x;
        node["y"] = rhs.y;
        node["z"] = rhs.z;

        return node;
    }
}

so I need to return a node, but the emitter can't convert to a node.

I need the object to like that:

GameObject:
  m_Layer: 0
  m_Pos: {x: 0.500000, y: 0.500000, z: 0.500000}

How can I do this?

回答1:

A while ago the node interface was extended in yaml-cpp to include a SetStyle() function adding the following line anywhere in encode should have the desired result

node.SetStyle(YAML::EmitterStyle::Flow);


标签: yaml-cpp