简体   繁体   English

重载函数的C ++地址

[英]C++ address of overloaded function

In my project I want to do something like following: 在我的项目中,我想执行以下操作:

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;
}

Basically, the third function returns a mapping of string to function address. 基本上,第三个函数返回string到函数地址的映射。 However, at this point, I get an error address of overloaded function with no contextual type information , which also makes sense, since I have overloaded the test0 function, and compiler at this point doesn't know the address of which function to take. 但是,在这一点上,我得到了一个address of overloaded function with no contextual type information的错误address of overloaded function with no contextual type information ,这也很有意义,因为我已经重载了test0函数,并且编译器此时不知道采用哪个函数的地址。 Is there any way I could address this problem, other than calling my functions different names? 除了用不同的名称调用函数以外,还有什么方法可以解决此问题?

You should define pointer type when getting function address: 获取函数地址时应定义指针类型:

#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;
}

working code online 在线工作代码

The easiest solution is to store the pointer to the overloaded function in a pointer, first: 最简单的解决方案是将指向重载函数的指针存储在指针中,首先:

#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.out $ ./每年
test0 [5] 测试0 [5]
test0 [10] 42 测试0 [10] 42

If you want to call the stored void* , then you have to make it a function pointer again. 如果要调用存储的void* ,则必须再次使其成为函数指针。 You can do that by eg reinterpret_cast<void(*)(int)>(p) . 您可以通过例如reinterpret_cast<void(*)(int)>(p)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM