C++ passing method pointer as template argument

前端 未结 5 944
攒了一身酷
攒了一身酷 2021-01-19 23:44

I have a caller function like this:

template
void CallMethod(T *object){
    (object->*method)(args);
}
         


        
5条回答
  •  礼貌的吻别
    2021-01-20 00:38

    At this point I have ascertained that you have an API that takes a function and a pointer and you need to supply it such. I assume that you must always supply it an A* pointer?

    If it is a very generic callback but must be a function (can't be a boost::function) and must be a pointer (possibly void*) then you need a function a bit like this:

    struct GenericHolder
    {
       boost::function0 func;
    };
    
    void GenericCallback( void * p )
    {
       GenericHolder * holder = static_cast< GenericHolder * >(p);
       holder->func();
       delete holder;
    }
    

    As in this case I am calling delete at call time, so I have assume we call new at invoke time, i.e. when you build up your pointer on which your call is made. Of course it might not be that your pointer you pass is deleted on first call, so manage the lifetime appropriately.

    If you are in control of the "other side" then don't do this by design but let that side hold the boost::function and just call it.

    Memory management can still be an issue you need to take care of. For example, when you call boost::bind it wraps things in a struct behind the scenes for you. If these are pointers you allocated with new you need to delete them at sometime. If they are references they must still be valid at the point of call. pointers to local variables can also be a problem. shared_ptrs are ideal, of course. And the bug tracking to the boost::bind error is very very hard to find if you use that concept a lot.

提交回复
热议问题