开发者

What does this mean: warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’

I have a member function in a class that has a callback, but the callback isn't strictly neccessary, so it has a default callback, which is empty. It seems to work fine, but I get an annoying warning:

warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’

I'm trying to figure out what it means and how to turn 开发者_C百科it off (or fix it if I really am doing something wrong). Here's some simple code:

class ClassName{
public:
    void doSomething(void (*callbackFunction)() = (void(*)()) &ClassName::doNothing){
        callbackFunction();
    }
    void doNothing(){}
};

int main(){
    ClassName x;
    x.doSomething();
    return 0;
}

Note: If I do this (without explicitly casting it as a void(*)()):

void doSomething(void (*callbackFunction)() = &ClassName::doNothing)

I get this:

main.cpp:3: error: default argument for parameter of type ‘void (*)()’ has type ‘void (ClassName::*)()’


The issue is that you're passing a pointer to an instance method rather than a static method. If you make doNothing a static method (which means no implicit instance argument), the warning goes away.

Specifically,

warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’

exactly is saying that it's converting from a member function of class ClassName, to a non-member function.

See also the C++ FAQ Lite entry about pointers to member functions and pointers to functions.


Free function pointer is not the same as class member function pointer, which requires an instance of the class at call site. Though a static member function will do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜