使用函数指针的STL映射

Jac*_*ack 38 c++ stl function-pointers map

我开发了一个具有许多内置函数的脚本引擎,所以为了调用任何函数,我的代码只是进入一个if .. else if .. else if检查名称的墙,但我想开发一个更有效的解决方案.

我应该使用带字符串的hashmap作为键和指针作为值吗?我怎么能用STL地图呢?

编辑:我想到的另一点:当然使用map会强制编译器不要内联函数,但是我的低效方法没有因函数调用的必要性而产生任何开销,它只是执行代码.

所以我想知道函数调用产生的开销是否会比拥有if..else链更好...否则我可以通过在运行时检查字符来最小化比较次数(将更长但更快).

GMa*_*ckG 45

无论您的功能签名是什么:

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)();
}
Run Code Online (Sandbox Code Playgroud)

请注意,ScriptFunction类型可以推广到std::function</* whatever*/>所以你可以支持任何可调用的东西,而不仅仅是函数指针.

  • 实际上,我已经完成了一些类似的东西,而且"unordered_map"的速度要快得多.我只有大约10,000件事,我描述了`map`和`unordered_map`. (3认同)
  • 而且确实没有必要使用像“unordered_map”这样的真正的哈希表。哈希表不会带来太多的元素带来性能优势,如果“map”在这种情况下更快,我什至不会感到惊讶。 (2认同)

mlo*_*kot 16

您还可以使用Boost.Function和Boost.Bind甚至允许您在某种程度上拥有异构函数的映射:

typedef boost::function<void, void> fun_t;
typedef std::map<std::string, fun_t> funs_t;
funs_t f;

void foo() {}
void goo(std::string& p) {}
void bar(int& p) {}

f["foo"] = foo;
f["goo"] = boost::bind(goo, "I am goo");
f["bar"] = boost::bind(bar, int(17));
Run Code Online (Sandbox Code Playgroud)

当然,它也可以是兼容原型的功能图.


Moh*_*hit 14

在C++ 11中,您可以执行以下操作:此接口仅需要返回类型,并且它会处理来自调用方的所有其他内容.

#include <string>
#include <iostream>
#include <map>
#include <vector>
#include <typeinfo>
#include <typeindex>
#include <cassert>

void fun1(void){
    std::cout<<"inside fun1\n";
}

int fun2(){
    std::cout<<"inside fun2\n";
    return 2;
}

int fun3(int a){
    std::cout<<"inside fun3\n";
    return a;
}

std::vector<int> fun4(){
    std::cout<<"inside fun4\n";
    std::vector<int> v(4,100);
    return v;
}

// every function pointer will be stored as this type
typedef void (*voidFunctionType)(void); 

struct Interface{

    std::map<std::string,std::pair<voidFunctionType,std::type_index>> m1;

    template<typename T>
    void insert(std::string s1, T f1){
        auto tt = std::type_index(typeid(f1));
        m1.insert(std::make_pair(s1,
                        std::make_pair((voidFunctionType)f1,tt)));
    }

    template<typename T,typename... Args>
    T searchAndCall(std::string s1, Args&&... args){
        auto mapIter = m1.find(s1);
        /*chk if not end*/
        auto mapVal = mapIter->second;

        // auto typeCastedFun = reinterpret_cast<T(*)(Args ...)>(mapVal.first); 
        auto typeCastedFun = (T(*)(Args ...))(mapVal.first); 

        //compare the types is equal or not
        assert(mapVal.second == std::type_index(typeid(typeCastedFun)));
        return typeCastedFun(std::forward<Args>(args)...);
    }
};

int main(){
    Interface a1;
    a1.insert("fun1",fun1);
    a1.insert("fun2",fun2);
    a1.insert("fun3",fun3);
    a1.insert("fun4",fun4);

    a1.searchAndCall<void>("fun1");
    int retVal = a1.searchAndCall<int>("fun3",2);
    a1.searchAndCall<int>("fun2");
    auto temp = a1.searchAndCall<std::vector<int>>("fun4");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是黄金。是否可以向混合添加成员函数?也许在某个时候将其转换为非成员类型?谢谢 (2认同)

And*_*asT 7

以上答案似乎给出了完整的概述,这只是你的第二个问题:

按键检索地图元素具有O(log n)复杂度.按键检索Hashmap具有O(1)复杂性+在碰撞情况下侧面有一些小东西.因此,如果函数名称具有良好的哈希函数,请使用它.您的实施将具有标准实施.应该没问题.

但请注意,低于一百个元素的任何东西都不会受益太多.

哈希映射的唯一缺点是碰撞.在您的情况下,hashmap将是相对静态的.您知道您支持的功能名称.因此,我建议您创建一个简单的测试用例,在其中使用所有键调用unordered_map <...> :: hash_function以确保没有任何冲突.在那之后,你可以忘掉它.

快速google有关哈希函数的潜在改进让我感到满意:

一个好的哈希函数

也许,根据您的命名约定,您可以改进函数的某些方面.


Jac*_*cob 6

好吧,您可以使用any_map存储具有不同签名的函数(但调用它会很麻烦),您可以使用int_map调用具有特定签名的函数(看起来更好)。

int FuncA()
{
    return 1;
}

float FuncB()
{
    return 2;
}


int main()
{
    // Int map
    map<string,int(*)()> int_map;
    int_map["A"] = FuncA;
    // Call it
    cout<<int_map["A"]()<<endl;

    // Add it to your map
    map<string, void(*)> any_map;
    any_map["A"] = FuncA;
    any_map["B"] = FuncB;

    // Call
    cout<<reinterpret_cast<float(*)()>(any_map["B"])()<<endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 你真的只是在 C++ 程序中编写了 `void main` 吗? (3认同)