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

Convert user data types in yaml-cpp

这是 here 教程中的示例: 有这样的class:

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

如何正确转换数据类型?

Vec3 的定义是您实际使用的定义吗?错误消息表明您需要 Vec3 的默认构造函数,它只找到 Vec3(double, double, double)(加上 copy/move)。

如果您定义了一个采用三个双精度值的构造函数,您还需要定义一个采用零参数的构造函数。