C++将函数指针一行放入映射中

标签 c++

在我的项目中,我有以下功能:

static void test0(void)
{
    printf("%s [%d]\n", __func__, __LINE__);
}

static void test0(int a)
{
    printf("%s [%d] %d\n", __func__, __LINE__, a);
}


static std::map<std::string, void*> getAddressMap()
{
    std::map<std::string, void*> addressmap;

    void (*select1)(void) = test0;  // will match void(void)
    addressmap["test0"]=reinterpret_cast<void *>(select1);

    void (*select2)(int) = test0;   // will match void(int)
    addressmap["test0"]=reinterpret_cast<void *>(select2);
    return addressmap;
}

此时您可以看到,为了将每个指针存储在 map 中,我需要定义一个特殊的指针,然后我才能将其存储在 map 中...

由于所有这些方法和 stub 都是从模板生成的,因此仅使用一行代码会更实用。所以,我的问题是,有没有一种方法可以在一行中完成?

最佳答案

转换函数指针(在转换为 void* 之前)应该工作得很好......

addressmap["test0"] = reinterpret_cast<void *>(static_cast<void(*)(void)>(test0));
addressmap["test0"] = reinterpret_cast<void *>(static_cast<void(*)(int)>(test0));

关于C++将函数指针一行放入映射中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45233425/

相关文章:

c++ - Unix 套接字卡在 recv 上,直到我在任何地方放置/删除断点

c++ - CMUSphix 不识别

c++ - 正在进行的返回值转换的说明

c++ - 为 C++ 类中基于模板的对象重载 <<

c++ - 传递我的引用 C++ 时使用类的公共(public)函数时出错

c++ - 在 std::vector 中删除、调试、发布

c++ - 如何将 "A1"样式的行+列规范作为输入?

c++ - 固定大小的容器,其中元素已排序并可以提供指向 C++ 中数据的原始指针

c++ - 从 MFC(c++) 应用程序启动的可执行 jar 中获取返回值

java - 是否会在编译时优化局部变量的一次性使用?