C++11 如何将函数地址从类1发送到类2
c++11/arm编译器v6.9/keil5 我有2个类(class1,class2)-我没有从class1向class2发送函数地址,但我不能-我必须定义我的函数静态-但我不想这样做C++11 如何将函数地址从类1发送到类2,c++11,static,arm,keil,C++11,Static,Arm,Keil,c++11/arm编译器v6.9/keil5 我有2个类(class1,class2)-我没有从class1向class2发送函数地址,但我不能-我必须定义我的函数静态-但我不想这样做 // ---------------------------- CLASS1.CPP ---------------------------- void CLASS1::ControlTransfer(uint8_t Physical_EPn, uint8_t bEPStatus) { // ... } vo
// ---------------------------- CLASS1.CPP ----------------------------
void CLASS1::ControlTransfer(uint8_t Physical_EPn, uint8_t bEPStatus) {
// ...
}
void CLASS1::init() {
class2.intHandler(2, ControlTransfer); // error: reference to non-static member function must be called
}
// ---------------------------- CLASS2.H ----------------------------
typedef void (TFnEPIntHandler) (uint8_t Physical_EPn, uint8_t bEPStatus);
// ---------------------------- CLASS2.CPP ----------------------------
TFnEPIntHandler *_apfnEPIntHandlers[16];
void CLASS2::intHandler( uint8_t num, TFnEPIntHandler *pfnHandler ) {
_apfnEPIntHandlers[ num ] = pfnHandler;
}
// _apfnEPIntHandlers used in my interrupt function
非静态成员函数如
CLASS1::ControlTransfer
在不知道调用它的CLASS1
对象的情况下无法调用。而像TFnEPIntHandler
这样的函数的原始指针并没有包含足够的信息来指定该对象
如果可以,请考虑将原始函数指针更改为更灵活的<代码> STD::函数< /C> >类型:
// In a header file:
#include <functional>
using TFnEPIntHandler = std::function<void(uint8_t, uint8_t)>;
// TFnEPIntHandler should now be used directly, not as a pointer.
// (Note a std::function can "act like" a null pointer.)
TFnEPIntHandler _apfnEPIntHandlers[16];
void CLASS2::intHandler( uint8_t num, TFnEPIntHandler pfnHandler ) {
_apfnEPIntHandlers[ num ] = std::move(pfnHandler);
}
// Replace CLASS1::init():
void CLASS1::init() {
// Use a lambda which captures the "this" pointer and can be
// converted to the std::function type. The function must not
// be used after this CLASS1 object is destroyed!
class2.intHandler(2, [this](uint8_t Physical_EPn, uint8_t bEPStatus)
{ ControlTransfer(Physical_EPn, bEPStatus); });
}
额外的void*
参数可以提供给CLASS2::intHandler
(这意味着应该有函数指针和额外的void*
数据的结构数组),或者提供给实际调用函数的其他逻辑,以更合适的为准
class CLASS1 {
// ...
private:
static void ControlTransferCB(uint8_t Physical_EPn,
uint8_t bEPStatus,
void* extra)
{
static_cast<CLASS1*>(extra)->ControlTransfer(Physical_EPn, bEPStatus);
}
// ...
};