从类型 'YAML::Node&' 的右值初始化 类型的非常量引用无效 'YAML::Node'

Invalid initialization of non-const reference of type 'YAML::Node&' from an rvalue of type 'YAML::Node'

本文关键字:Node YAML 类型 常量 无效 引用 非常 初始化      更新时间:2023-10-16

我正在编写一个函数,该函数会将值加载并保存到.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关键字使其恒定。但是,就像我之前说的,我也需要能够保存价值。因此,我必须能够修改节点并且不能使其恒定。我现在应该做什么有点迷茫。我的代码为.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;
    }
}

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,因此它不能绑定到非常量左值引用,因为这意味着绑定到临时对象。

所以删除&,这是它的设计使用方式:

YAML::Node child = parent[*currentToken];

在第一行:

bool ReadParameter(YAML::Node parent,