In some scenarios, it may be necessary to pass a Boost::function to a method that anticipates a standard function pointer (demonstrating the same signature). This can lead to compilation errors.
typedef void TriggerProc_type(Variable*, void*); void InitVariable(TriggerProc_type *proc); boost::function<void (Variable*, void*)>& triggerProc ... InitVariable(triggerProc); // Error: cannot convert parameter 1
Eliminating Boost::function and referencing the bound functor immediately leads to analogous errors:
error C2664: 'blah(void (__cdecl *)(type *,void *))' : cannot convert parameter 1 from 'boost::_bi::bind_t<R,F,L>>' to 'void (__cdecl *)(type *,void *)'
The commonly accepted solution is limited as it only operates successfully in trivial cases. A more effective approach involves employing a shim function, which abides by the callback signature, ascertains the applicable Boost::function to invoke, and executes it.
typedef void (*CallbackType)(int x, void* user_data); void RegisterCallback(CallbackType cb, void* user_data); void MyCallback(int x, void* userData) { boost::function<void(int)> pfn = static_cast<boost::function<void(int)> &>(userData); pfn(x); } boost::function<void(int)> fn = boost::bind(myFunction(5)); RegisterCallback(MyCallback, &fn);
This method ensures compatibility between Boost::function and Boost::bind, enabling their seamless integration with C callbacks. However, if the callback signature lacks a user data pointer, this approach becomes infeasible. Nonetheless, such callback structures are inherently limited in practical applications and warrant revision.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!