在我的项目中,我想做如下事情:
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
函数,而且编译器此时不知道要使用哪个函数的地址。除了用不同的名字称呼我的函数之外,还有什么办法可以解决这个问题吗?
发布于 2017-07-17 14:20:20
最简单的解决方案是将指向重载函数的指针存储在指针中,首先:
#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)
这样做。
发布于 2017-07-17 14:20:27
在获取函数地址时,应定义指针类型:
#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;
}
https://stackoverflow.com/questions/45146522
复制相似问题