在函數(shù)體內(nèi)定義函數(shù)

使用lambda表達(dá)式,可以臨時(shí)建立指定類型的函數(shù)

AbsBehaviorTree BuildTreeFromXML(const QDomElement& bt_root, const NodeModels& models )
{
    AbsBehaviorTree tree;

    if( bt_root.tagName() != "BehaviorTree" )
    {
        throw std::runtime_error( "Expecting a node called <BehaviorTree>");
    }

    //-------------------------------------定義lambda表達(dá)式,在函數(shù)內(nèi)定義函數(shù)
    std::function<void(AbstractTreeNode* parent, QDomElement)> recursiveStep;
    recursiveStep = [&](AbstractTreeNode* parent, QDomElement xml_node)
    {
        // The nodes with a ID used that QString to insert into the registry()
        QString modelID = xml_node.tagName();
        if( xml_node.hasAttribute("ID") )
        {
            modelID = xml_node.attribute("ID");
        }

        AbstractTreeNode tree_node;

        auto model_it = models.find(modelID);
        if( model_it ==  models.end() )
        {
             throw std::runtime_error( (QString("This model has not been registered: ") + modelID).toStdString() );
        }
        tree_node.model = model_it->second;

        if( xml_node.hasAttribute("name") )
        {
            tree_node.instance_name = ( xml_node.attribute("name") );
        }
        else{
            tree_node.instance_name = modelID;
        }

        auto attributes = xml_node.attributes();
        for( int attr=0; attr < attributes.size(); attr++ )
        {
            auto attribute = attributes.item(attr).toAttr();
            if( attribute.name() != "ID" && attribute.name() != "name")
            {
                tree_node.ports_mapping.insert( { attribute.name(), attribute.value() } );
            }
        }

        auto added_node = tree.addNode(parent, std::move(tree_node));

        for (QDomElement  child = xml_node.firstChildElement( )  ;
             !child.isNull();
             child = child.nextSiblingElement( ) )
        {
            recursiveStep( added_node, child );
        }
    };

    auto first_child = bt_root.firstChildElement();
    if( first_child.tagName() == "Root")
    {
        QMessageBox::question(nullptr,
                              "Fix your file!",
                              "Please remove the node <Root> from your <BehaviorTree>",
                              QMessageBox::Ok );
        first_child = first_child.firstChildElement();
    }

    // start recursion
    recursiveStep( nullptr, first_child );

    return tree;
}

std::function這個(gè)關(guān)鍵字很好用,配合lambda表達(dá)式,可以再一個(gè)函數(shù)內(nèi)容很方便的封裝功能,并且可以讓代碼看著很整潔,但是這樣的代碼并不能向前兼容,如果有些工作環(huán)境要求同時(shí)兼容不同的版本,就要注意少用。

如果在多個(gè)函數(shù)中,有著公用的部分,也是需要進(jìn)行局部重構(gòu),將這些公用的部分提成私有成員函數(shù),或者是調(diào)整為inline類型的全局函數(shù)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容