在yaml-cpp中转换用户数据类型

时间:2016-12-01 13:32:24

标签: yaml yaml-cpp

这是来自here的教程的示例: 有这样的课程:

struct Vec3 { double x, y, z; bool operator==(Vec3& other) const { return other.x == this->x && other.y == this->y && other.z == this->z;}};

此代码用于将yaml数据转换为用户对象(Vec3):

namespace YAML {
template<>
struct convert<Vec3> {
  static bool decode(const Node& node, Vec3& rhs) {
    if(!node.IsSequence() || node.size() != 3) {
      return false;
    }
    rhs.x = node[0].as<double>();
    rhs.y = node[1].as<double>();
    rhs.z = node[2].as<double>();
    return true;
  }
};
}

现在我测试一下:

YAML::Node node = YAML::Load("start: [1, 3, 0]");
Vec3 v = node["start"].as<Vec3>();

但我有一个错误:

In file included from /usr/local/include/yaml-cpp/yaml.h:17:0,
                 from /home/ken/ClionProjects/First/yaml-cpp/first_yaml.cpp:5:
/usr/local/include/yaml-cpp/node/impl.h: In instantiation of ‘T YAML::as_if<T, void>::operator()() const [with T = Vec3]’:
/usr/local/include/yaml-cpp/node/impl.h:146:31:   required from ‘T YAML::Node::as() const [with T = Vec3]’
/home/ken/ClionProjects/First/yaml-cpp/first_yaml.cpp:52:37:   required from here
/usr/local/include/yaml-cpp/node/impl.h:122:7: error: no matching function for call to ‘Vec3::Vec3()’
     T t;
       ^
/home/ken/ClionProjects/First/yaml-cpp/first_yaml.cpp:14:5: note: candidate: Vec3::Vec3(double, double, double)
     Vec3(double a, double b, double c){
     ^
/home/ken/ClionProjects/First/yaml-cpp/first_yaml.cpp:14:5: note:   candidate expects 3 arguments, 0 provided
/home/ken/ClionProjects/First/yaml-cpp/first_yaml.cpp:12:8: note: candidate: constexpr Vec3::Vec3(const Vec3&)
 struct Vec3 {
        ^
/home/ken/ClionProjects/First/yaml-cpp/first_yaml.cpp:12:8: note:   candidate expects 1 argument, 0 provided
/home/ken/ClionProjects/First/yaml-cpp/first_yaml.cpp:12:8: note: candidate: constexpr Vec3::Vec3(Vec3&&)
/home/ken/ClionProjects/First/yaml-cpp/first_yaml.cpp:12:8: note:   candidate expects 1 argument, 0 provided
CMakeFiles/First.dir/build.make:62: recipe for target 'CMakeFiles/First.dir/yaml-cpp/first_yaml.cpp.o' failed

如何正确转换数据类型?

1 个答案:

答案 0 :(得分:1)

SafeArrayDestroy(psa)的定义是您实际使用的那个吗?该错误消息表明您需要Vec3的默认构造函数,并且只找到Vec3(加上复制/移动)。

如果你定义了一个带三个双精度的构造函数,你还需要定义一个零参数的构造函数。