使用函数指针的 STL 映射

2021-12-10 00:00:00 function-pointers c++ map stl

我开发了一个具有许多内置函数的脚本引擎,所以要调用任何函数,我的代码只是进入了一个 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.

相关文章