Disabling “bad function cast” warning

后端 未结 3 1008
傲寒
傲寒 2020-12-11 02:43

I\'m receiving the following warning:

warning: converting from \'void (MyClass::*)(byte)\' to \'void (*)(byte)\'

This is because I need to

3条回答
  •  北海茫月
    2020-12-11 03:19

    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.

提交回复
热议问题