Disabling “bad function cast” warning

后端 未结 3 1006
傲寒
傲寒 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:06

    Also, this may be helpful

    union FuncPtr    
    {
      void (* func)(MyClass* ptr, byte);
      void (MyClass::* mem_func)(byte);
    };
    
    0 讨论(0)
  • 2020-12-11 03:19

    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:

    void foo (byte); // normal function
    struct MyClass {
      void foo (byte); // member function 
    }
    

    Now you may feel that, foo(byte) and MyClass::foo(byte) have same signature, then why their function pointers are NOT same. It's because, MyClass::foo(byte) is internally resolved somewhat as,

    void foo(MyClass* const this, byte);
    

    Now you can smell the difference between them.

    Declare pointer to member function as,

    void (MyClass::*ptr)(byte) = &MyClass::foo;
    

    You have to use this ptr with the object of MyClass, such as:

    MyClass obj;
    obj.*ptr('a');
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题