从类型"void*"到类member_function指针的强制转换无效

invalid cast from type âvoid*â to class member_function pointer

本文关键字:指针 转换 无效 function void 类型 到类 member      更新时间:2023-10-16
typedef A::T*(Processor::*myMethodType)(const FDS::T*);
myMethodType temp = NULL;
temp = reinterpret_cast<myMethodType> (myInterface.findMap(moname)))

注意: 处理器是一个实例化模板类的类。 myMethodType 是成员指针函数指针。

注意:findMap 返回一个 void*,如下所示,myinterface 是一个映射

template <class Implementor>
void* Interface<Implementor>::findMap(std::string &name){
if (myInterface.find(moname) != myInterface.end()) {
return myInterface.find(moname)->second;
}
return NULL;
}

====

============================================================低于错误 -

error: invalid cast from type âvoid*â to type âProcessor::myMethodType {aka T* (Processor::*)(const T*)}â
if((temp = reinterpret_cast<myMethodType> (myInterface.findMap(moname))) != NULL)

问题 - 为什么我会收到此错误,尽管我将其转换为member_class_pointer? 为什么转换无效?

尝试到现在:

尝试以下方法---https://stackoverflow.com/questions/1307278/casting-between-void-and-a-pointer-to-member-function

void myclass::static_fun(myclass *instance, int arg)
{
instance->nonstatic_fun(arg);
}

但到目前为止没有运气!!

常规指针不同于指向成员的指针。自reinterpret_cast转换以来(见 https://en.cppreference.com/w/cpp/language/reinterpret_cast( 指针可以转换为另一个指针或整型类型,但不能转换为指向成员的指针

不能在函数指针和对象指针(如void*(之间进行强制转换。如果需要具有多个函数指针类型的映射,可以将它们转换为更多的函数指针类型,例如void*(*)()。函数指针在调用之前必须转换回原始类型。

如果不需要多个函数指针类型,则可以使用myMethodType映射。