Roma  Karageorgievich Roma Karageorgievich - 2 days ago 6
YAML Question

Convert user data types in yaml-cpp

This is example from tutorial from here:
There is such 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;}};


This code for converting yaml data to user object(
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;
}
};
}


Now I test it:

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


But I have an error:

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


How convert data types correctly?

Answer

Is the definition of Vec3 the one you're actually using? The error message indicates that you need a default constructor for Vec3, and it only found Vec3(double, double, double) (plus copy/move).

If you defined a constructor that takes three doubles, you also need to define one that takes zero arguments.

Comments