lundi 27 juillet 2020

c++ void function not returning control to the caller after the condition is met

I am having an issue returning out of a void function. Here is the function:

void findTreeNodeRecursively(unsigned indent, const TreeNode* node, const std::function<bool(const TreeNode*)>& name_checker){

    for (unsigned i = 0; i < indent; i++)
    {
        std::cout << "   ";
    }
    if (!node)
    {
        std::cout << "!nullptr!" << std::endl;
        return;
    }

    indent++;

    if(name_checker(node) == true){
        return;
    }

    if (auto control = dynamic_cast<const ControlNode*>(node))
    {
        for (const auto& child : control->children())
        {
            findTreeNodeRecursively(indent, child, name_checker);
        }
    }
    else if (auto decorator = dynamic_cast<const DecoratorNode*>(node))
    {
        findTreeNodeRecursively(indent, decorator->child(), name_checker);
    }
}

Here is the file where this function is implemented:

static const char* xml_text = R"(

 <root main_tree_to_execute = "MainTree" >

     <BehaviorTree ID="MainTree">
        <Sequence name="root_sequence">
            <ApproachObject name="approach"/>
            <CheckBattery   name="battery_ok"/>
            <OpenGripper    name="open_gripper"/>
            <ApproachObject name="approach_object"/>
            <CloseGripper   name="close_gripper"/>
        </Sequence>
     </BehaviorTree>

 </root>
 )";
int main(){
    auto tree = factory.createTreeFromText(xml_text);
    const std::string name_to_find = "open_gripper";
    auto name_checker = [&name_to_find](const TreeNode* node) -> bool {
      std::cout<<node->name()<<std::endl;
      if (node->name() == name_to_find)
      {
          return true;
      }
      else
      {
          return false;
      }
    };

    findTreeNodeRecursively(0, tree.root_node, name_checker);

    return 0;
}

I can see the output printed when the name (input) is found, which returns true. The void function should return if the lambda (or name_checker) function returns true, but it still implementing remaining part of the function.

Aucun commentaire:

Enregistrer un commentaire