問題描述
我開發了一個具有許多內置函數的腳本引擎,所以要調用任何函數,我的代碼只是進入了一個 if .. else if .. else if
墻檢查名稱,但我想開發一個更有效的解決方案.
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.
我應該使用 hashmap 以字符串作為鍵和指針作為值嗎?我怎么能通過使用 STL 映射來做到這一點?
Should I use a hashmap with strings as keys and pointers as values? How could I do it by using an STL map?
編輯:我想到的另一點是:當然使用映射會迫使編譯器不內聯函數,但我的低效方法沒有因函數調用的必要性而產生的任何開銷,它只是執行代碼.
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.
所以我想知道函數調用產生的開銷是否會比使用 if..else
鏈更好..否則我可以通過在運行時檢查一個字符來最小化比較次數(會更長但更快).
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).
推薦答案
無論你的函數簽名是什么:
Whatever your function signatures are:
typedef void (*ScriptFunction)(void); // function pointer type
typedef std::unordered_map<std::string, ScriptFunction> script_map;
// ...
void some_function()
{
}
// ...
script_map m;
m.emplace("blah", &some_function);
// ...
void call_script(const std::string& pFunction)
{
auto iter = m.find(pFunction);
if (iter == m.end())
{
// not found
}
(*iter->second)();
}
注意 ScriptFunction
類型可以泛化為 std::function</*whatever*/>
這樣你就可以支持任何可調用的東西,而不僅僅是函數指針.
Note that the ScriptFunction
type could be generalized to std::function</* whatever*/>
so you can support any callable thing, not just exactly function pointers.
這篇關于使用函數指針的 STL 映射的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!