2017-09-02 34 views
2
#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"); 
+3

为什么会有函数指针paramater'无效*':

但是,如果你给编译器足够的信息可以推断出它? - >'void(* CallbackInt)(int);' –

+2

为什么所有这些演员? - >'CallbackInt = &cb;'(由@FilipKočica修改后) –

+1

用重载'operator()'编写调用包装会更好。如果您需要将回调函数存储在单独的变量中,那么您需要正确声明函数指针类型而不是void(void *);' – VTT

回答

6

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; 

} 
0

对于第一个错误,使用静态投来指定要超载,像here

对于剩下的,你就不能施放一个int或者浮动到void *有意义。不知道你想在这里做什么。

CallbackInt或许应该采取一个int参数...

+1

如果函数指针变量类型设置正确,则不需要使用任何类型转换。 – VTT

+0

这是真的,但我不确定OP在做什么。 – Khoyo

相关问题