使用函数指针的STL映射 [英] Using a STL map of function pointers
问题描述
if .. else if .. else if
墙上检查名称,但我想开发一个更有效的解决方案。 我应该使用具有字符串的键作为键和指针的 hashmap ?如何使用STL地图?另外还有一点出现在我脑海里:当然使用地图会强制编译器不要内联函数,但是我的低效方法没有任何由于函数调用的必要性而产生的开销,它只是执行代码。
所以我想知道函数调用生成的开销是否会比$ code> if..else chain更好,否则我可以通过在运行时检查一个字符来最小化比较的数量(将会更长但更快)。 p>
无论您的功能签名如何:
typedef void(* ScriptFunction)(void); //函数指针类型
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< / *无论* />
,所以你可以支持任何可调用的东西,而不仅仅是完全的函数指针。
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.
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.
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)();
}
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映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!