以下代码实现的功能是void*(class::*)(void*) 转化为void*(*)(void*) 即将类的成员函数指针转化为一般的函数指针
#include <string>
#include <stdio.h>
template <typename T,typename F>
T supercast(F f)
{
union FT
{
T t;
F f;
};
FT ft;
ft.f=f;
return ft.t; //此为技巧,利用联合将地址返回。
}
class Apple{
public:
Apple(std::string color)
:color_(color){}
void what()
{
printf("this is a apple!\n");
//printf("this is a %s apple!\n", color_.c_str());
}
private:
std::string color_;
};
int main(int argc, char *argv[])
{
typedef void(what_t)(Apple*);
what_t* what_apple = supercast<what_t*>(&Apple::what);
Apple red_apple("red");
what_apple(&red_apple);
return 0;
}不过当使用注释那行代码的时候,即要转化的成员函数访问成员变量的时候,转过来的普通函数会发生非法访问错误!
本文介绍了一个C++模板函数如何将类的成员函数指针转换为普通的函数指针,通过使用模板和联合类型来实现这一目标。特别关注了转换过程中的注意事项,特别是当成员函数试图访问类内部状态时可能会遇到的问题。


被折叠的 条评论
为什么被折叠?



