#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;
}
Above is my code which has three function , I want to create three callbacks which will call overloaded function depending on their parameter. CallbackInt used to call cb function with int as parameter and similarly rest two.
But when compiling with it gives me error as below.
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) Compiler does not know, which overload of cb
to chose.
2) Even if it did know, it would not convert from void*
to, say void(*)(int)
, without any explicit conversion.
However, it can deduce it if you give compiler enough information:
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;
}
I know this is an old post, but I recently got this error and my issue was that I wasn't declaring the variable I was setting the result of my function to. Not sure why this error was the one it gave for that issue, but hopefully this helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With