我正在编写一个函数,可以将值加载并保存到.yaml
文件中(取决于toggle
输入的内容;' S'用于保存和' L'用于加载)。出于某种原因,我在行中出现Invalid initialization of non-const reference of type 'YAML::Node&' from an rvalue of type 'YAML::Node'
错误:
YAML::Node& child = parent[*currentToken];
我在网上找到的解决方案是通过添加const
关键字使其保持不变。但是,正如我之前所说,我也需要能够节省价值。因此,我必须能够修改节点,并且不能使它成为const。我现在应该做些什么,我有点迷茫。我的代码接受.yaml
文件和最后一个节点中第一个节点的迭代器。这是我的代码:
bool ReadParameter(YAML::Node& parent,
boost::tokenizer< boost::char_separator< char > >::iterator& currentToken,
const boost::tokenizer< boost::char_separator< char > >::iterator& lastToken, float& value,
char toggle) {
/*
* When we reach the last token, the distance between the iterators is 1. At this point we must
* check to see if the token node exists in the yaml file. If it does store the value associated
* with the token key in the variable `value` to load or store the value back into the yaml file to save.
*/
if (distance(currentToken, lastToken) == 1) {
if (parent[*(currentToken)].IsScalar()) {
if (toggle == 'L') { // Load
value = parent[*(currentToken)].as< float >();
}
else if (toggle == 'S') { // Save
parent[*(currentToken)] = value;
}
return true;
} else {
printf("Key %s does not give a scalar value.\n", (*currentToken).c_str());
return false;
}
}
// If the node is a map, get it's child. Else, our path does not exist.
if (parent.IsMap()) {
YAML::Node& child = parent[*currentToken];
// If there is no child node, return false
if (child.IsNull()) {
printf("There are no more child nodes.\n");
return false;
}
// Iterate to the next token.
return ReadParameter(child, ++currentToken, lastToken, value, toggle);
} else {
printf("Too many parameters, the parameter path is incorrect.\n");
return false;
}
}
答案 0 :(得分:1)
YAML::Node
已经是参考语义类型。无需将YAML::Node
的实例绑定到引用。它们被设计为按值传递,但行为类似于引用。例如:
YAML::Node a = 42;
YAML::Node b = a;
b = 43; // both a and b now contain the value 43
parent[*currentToken]
按值返回YAML::Node
,因此它不能绑定到非const左值引用,因为这意味着绑定到临时对象。
请删除&
,这是设计使用的方式:
YAML::Node child = parent[*currentToken];
在第一行:
bool ReadParameter(YAML::Node parent,