在CPP中获取函数指针typecase中的错误

时间:2017-11-21 13:28:00

标签: c++

我在Regwrite课程中有以下成员功能。

unsigned int RegWrite::register_write(unsigned int reg_addr, unsigned int value) {
//Function definition
}

我想将上述功能分配给非类功能指针。

unsigned int (*REG_WR_FUNC) (unsigned int addr, unsigned int val);

void register_write_access(REG_WR_FUNC wr_func) {
   g_wr_func = wr_func;
}

在另一个Regwrite成员函数中,我已经传递了register_write函数。

unsigned int RegWrite::init() {
register_write_access(register_write);
}

我在类型转换中遇到错误,有人帮忙解决错误吗?

error: cannot convert 'unsigned int (RegWrite::*)(unsigned int, unsigned int) {aka unsigned int (RegWrite::*)(unsigned int, unsigned int)}' to 'REG_WR_FUNC {aka unsigned int (*)(unsigned int, unsigned int)}' for argument '1' to 'void customer_register_write_access(REG_WR_FUNC)'

1 个答案:

答案 0 :(得分:0)

为了在函数地址旁边调用register_write,还必须提供this指针。

因此成员函数actual接受类类型的隐藏指针参数。

您必须在通话时或绑定时提供this指针。

如果在绑定时提供this,您可以使用std::bind创建一个存储成员函数指针和this指针的函数对象。

如果在通话时可以访问this,请使用以下表示法:

// the function pointer must be a member function pointer.
unsigned int (RegWrite::*REG_WR_FUNC) (unsigned int addr, unsigned int val);

REG_WR_FUNC wr_func;
(this->*wr_func)(args...);