重载函数没有上下文类型信息
问题描述:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
void cb(int x)
{
std::cout <<"print inside integer callback : " << x << "\n" ;
}
void cb(float x)
{
std::cout <<"print inside float callback :" << x << "\n" ;
}
void cb(std::string& x)
{
std::cout <<"print inside string callback : " << x << "\n" ;
}
int main()
{
void(*CallbackInt)(void*);
void(*CallbackFloat)(void*);
void(*CallbackString)(void*);
CallbackInt=(void *)cb;
CallbackInt(5);
CallbackFloat=(void *)cb;
CallbackFloat(6.3);
CallbackString=(void *)cb;
CallbackString("John");
return 0;
}
以上是我的代码,它有三个函数,我想创建三个回调,它将根据它们的参数调用重载函数。 CallbackInt用于以int作为参数调用cb函数,同样地休息两个。重载函数没有上下文类型信息
但是,当它编译给我错误如下。
function_ptr.cpp: In function ‘int main()’:
function_ptr.cpp:29:21: error: overloaded function with no contextual type information
CallbackInt=(void *)cb;
^~
function_ptr.cpp:30:14: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
CallbackInt(5);
^
function_ptr.cpp:32:23: error: overloaded function with no contextual type information
CallbackFloat=(void *)cb;
^~
function_ptr.cpp:33:18: error: cannot convert ‘double’ to ‘void*’ in argument passing
CallbackFloat(6.3);
^
function_ptr.cpp:35:24: error: overloaded function with no contextual type information
CallbackString=(void *)cb;
^~
function_ptr.cpp:36:24: error: invalid conversion from ‘const void*’ to ‘void*’ [-fpermissive]
CallbackString("John");
答
1)编译器不知道,cb
超载选择哪个。
2)即使它知道,它也不会从void*
转换为void(*)(int)
,没有任何明确的转换。
void cb(int x)
{
std::cout <<"print inside integer callback : " << x << "\n" ;
}
void cb(float x)
{
std::cout <<"print inside float callback :" << x << "\n" ;
}
void cb(const std::string& x)
{
std::cout <<"print inside string callback : " << x << "\n" ;
}
int main()
{
void(*CallbackInt)(int);
void(*CallbackFloat)(float);
void(*CallbackString)(const std::string&);
CallbackInt = cb;
CallbackInt(5);
CallbackFloat = cb;
CallbackFloat(6.3);
CallbackString = cb;
CallbackString("John");
return 0;
}
为什么会有函数指针paramater'无效*':
但是,如果你给编译器足够的信息可以推断出它? - >'void(* CallbackInt)(int);' –
为什么所有这些演员? - >'CallbackInt = &cb;'(由@FilipKočica修改后) –
用重载'operator()'编写调用包装会更好。如果您需要将回调函数存储在单独的变量中,那么您需要正确声明函数指针类型而不是void(void *);' – VTT