Why callback functions needs to be static when dec

2019-01-07 23:20发布

I was trying to declare a callback function in class and then somewhere i read the function needs to be static but It didn't explain why?

#include <iostream>
using std::cout;
using std::endl;

class Test
{
public:
    Test() {}

    void my_func(void (*f)())
    {
        cout << "In My Function" << endl;
        f(); //Invoke callback function
    }

    static void callback_func()
    {cout << "In Callback function" << endl;}
};

int main()
{
    Test Obj;
    Obj.my_func(Obj.callback_func);
}

标签: c++ callback
6条回答
做自己的国王
2楼-- · 2019-01-07 23:53

Marshal Cline gives you the complete answer here . The whole section contains everything you need to know.

To summarize it can explain that you need a static member because the this pointer isn't needed (unlike normal member methods). But it also covers that using a static may not be enough for all compilers since C++ calling convention might be different between C and C++.

So the recommendation is to use an extern "C" non-member function.

查看更多
混吃等死
3楼-- · 2019-01-08 00:07

A member function is a function that need a class instance to be called on. Members function cannot be called without providing the instance to call on to. That makes it harder to use sometimes.

A static function is almost like a global function : it don't need a class instance to be called on. So you only need to get the pointer to the function to be able to call it.

Take a look to std::function (or std::tr1::function or boost::function if your compiler doesn't provide it yet), it's useful in your case as it allow you to use anything that is callable (providing () syntax or operator ) as callback, including callable objects and member functions (see std::bind or boost::bind for this case).

查看更多
甜甜的少女心
4楼-- · 2019-01-08 00:07

Callbacks need to be static so that they don't have an implicit this parameter as the first argument in their function signature.

查看更多
Luminary・发光体
5楼-- · 2019-01-08 00:08

Non-static methods require a 'this' instance, and can only be called upon an object instance.

However, it is possible to use non-static callbacks, but they are syntactically much harder to write. See http://www.newty.de/fpt/callback.html#member for an explanation.

查看更多
倾城 Initia
6楼-- · 2019-01-08 00:15

If you use function pointers, the runtime environment can't pass a reference to an instance when calling the function. But you may use std::mem_fun<>, in to use functors and member methods.

查看更多
我命由我不由天
7楼-- · 2019-01-08 00:16

It needs to be static so that the function signature matches. When a member function is called, a hidden parameter is included in the call (i.e. the "this" pointer). In static member functions the this pointer is not passed as a parameter.

查看更多
登录 后发表回答