#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");
爲什麼會有函數指針paramater'無效*':
但是,如果你給編譯器足夠的信息可以推斷出它? - >'void(* CallbackInt)(int);' –
爲什麼所有這些演員? - >'CallbackInt = &cb;'(由@FilipKočica修改後) –
用重載'operator()'編寫調用包裝會更好。如果您需要將回調函數存儲在單獨的變量中,那麼您需要正確聲明函數指針類型而不是void(void *);' – VTT