問(wèn)題描述
我開(kāi)發(fā)了一個(gè)具有許多內(nèi)置函數(shù)的腳本引擎,所以要調(diào)用任何函數(shù),我的代碼只是進(jìn)入了一個(gè) if .. else if .. else if
墻檢查名稱(chēng),但我想開(kāi)發(fā)一個(gè)更有效的解決方案.
I developed a scripting engine that has many built-in functions, so to call any function, my code just went into an if .. else if .. else if
wall checking the name but I would like to develop a more efficient solution.
我應(yīng)該使用 hashmap 以字符串作為鍵和指針作為值嗎?我怎么能通過(guò)使用 STL 映射來(lái)做到這一點(diǎn)?
Should I use a hashmap with strings as keys and pointers as values? How could I do it by using an STL map?
編輯:我想到的另一點(diǎn)是:當(dāng)然使用映射會(huì)迫使編譯器不內(nèi)聯(lián)函數(shù),但我的低效方法沒(méi)有因函數(shù)調(diào)用的必要性而產(chǎn)生的任何開(kāi)銷(xiāo),它只是執(zhí)行代碼.
EDIT: Another point that came into my mind: of course using a map will force the compiler not to inline functions, but my inefficient approach didn't have any overhead generated by the necessity of function calls, it just executes code.
所以我想知道函數(shù)調(diào)用產(chǎn)生的開(kāi)銷(xiāo)是否會(huì)比使用 if..else
鏈更好..否則我可以通過(guò)在運(yùn)行時(shí)檢查一個(gè)字符來(lái)最小化比較次數(shù)(會(huì)更長(zhǎng)但更快).
So I wonder if the overhead generated by the function call will be any better than having an if..else
chain.. otherwise I could minimize the number of comparisons by checking a character at runtime (will be longer but faster).
推薦答案
無(wú)論你的函數(shù)簽名是什么:
Whatever your function signatures are:
注意 ScriptFunction
類(lèi)型可以泛化為 std::function</*whatever*/>
這樣你就可以支持任何可調(diào)用的東西,而不僅僅是函數(shù)指針.
Note that the ScriptFunction
type could be generalized to std::function</* whatever*/>
so you can support any callable thing, not just exactly function pointers.
這篇關(guān)于使用函數(shù)指針的 STL 映射的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!