Disabling “bad function cast” warning

后端 未结 3 1023
傲寒
傲寒 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

    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');
    

提交回复
热议问题