Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

c++ - Disabling "bad function cast" warning

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...