首页  >  文章  >  后端开发  >  如何将 Boost::function 传递给需要函数指针的方法?

如何将 Boost::function 传递给需要函数指针的方法?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-11-14 16:44:02388浏览

How to Pass a Boost::function to a Method Expecting a Function Pointer?

Deriving a Plain Function Pointer from Boost::function

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.

Conversion 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

Avoiding Boost::function

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>&gt;' to 'void (__cdecl *)(type *,void *)'

Proposed Solution

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.

以上是如何将 Boost::function 传递给需要函数指针的方法?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn