2017-09-02 38 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

相關問題