I'm receiving the following warning:
warning: converting from 'void (MyClass::*)(byte)' to 'void (*)(byte)'
This is because I need to pass as argument a member function instead of an ordinary function. But the program is running correctly.
I'd like to disable this warning (Wno-bad-function-cast doesn't work for C++) or to implement a different way to pass a member function.
You can't pass a function that takes two arguments to a place that expects a function that takes one. Can't be done, forget about it, period, end of story. The caller passes one argument to your function. It doesn't know about the second argument, it doesn't pass it to your function, you can't make it do what you want however hard you try.
For the very same reason you can't pass a non-static member function where a regular function is expected. A member function needs an object to operate on. Whatever code calls your function doesn't know about the object, there's no way to pass it the object, and there's no way to make it use the right calling sequence that takes the object into account.
Interfaces that take user's functions, without taking additional data that the user might want to pass to his function, are inherently evil. Look at the
qsort()
function from the C standard library. That's an example of an evil interface. Suppose you want to sort an array of string according to some collation scheme defined externally. But all it accepts is a comparison function that takes two values. How do you pass that collation scheme to your comparison function? You can't, and so if you want it working, you must use an evil global variable, with all the strings attached to it.That's why C++ has moved away from passing function pointers around, and towards function objects. Function objects can encapsulate whatever data you want.
Also, this may be helpful
No. Take this warning seriously. You should rather change your code to handle this scenario.
Pointer to member function(
void (MyClass::*)(byte)
) and normal function pointer (void (*)(byte)
) are entirely different. See this link. You cannot cast them just like that. It results in undefined behavior or crash.See here, how they are different:
Now you may feel that,
foo(byte)
andMyClass::foo(byte)
have same signature, then why their function pointers are NOT same. It's because,MyClass::foo(byte)
is internally resolved somewhat as,Now you can smell the difference between them.
Declare pointer to member function as,
You have to use this
ptr
with the object ofMyClass
, such as: