使用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ù)。