首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >过载函数的C++地址

过载函数的C++地址
EN

Stack Overflow用户
提问于 2017-07-17 14:10:28
回答 2查看 2.5K关注 0票数 0

在我的项目中,我想做如下事情:

代码语言:javascript
运行
复制
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*> initializeAddressMap()
{
    std::map<std::string, void*> addressmap;
    addressmap["test0"] = (void*) &test0;    // ERROR HERE <------
    return addressmap;
}

基本上,第三个函数返回string到函数地址的映射。但是,此时,我得到了一个错误address of overloaded function with no contextual type information,这也是有意义的,因为我已经重载了test0函数,而且编译器此时不知道要使用哪个函数的地址。除了用不同的名字称呼我的函数之外,还有什么办法可以解决这个问题吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-17 14:20:20

最简单的解决方案是将指向重载函数的指针存储在指针中,首先:

代码语言:javascript
运行
复制
#include <cstdio>

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

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

int main(void) {
    void (*select1)(void) = test0;  // will match void(void)
    void (*select2)(int) = test0;   // will match void(int)

    select1();
    select2(42);

    return 0;
}

$./a. test0 5 test0 10 42

如果要调用存储的void*,则必须再次使其成为函数指针。你可以通过reinterpret_cast<void(*)(int)>(p)这样做。

票数 1
EN

Stack Overflow用户

发布于 2017-07-17 14:20:27

在获取函数地址时,应定义指针类型:

代码语言:javascript
运行
复制
#include <iostream>

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

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

int main()
{
    using t_pf1 = void (*)(void);
    using t_pf2 = void (*)(int);
    ::std::cout << (uintptr_t) t_pf1{&test} << "\n"
      << (uintptr_t) t_pf2{&test} << ::std::endl;
    return 0;
}

在线工作代码

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45146522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档