将类函数指针转换为void *,反之亦然 [英] Converting class function pointer to void* or vice versa

查看:762
本文介绍了将类函数指针转换为void *,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较两个函数的地址相等。我存储的函数的类型是已知的。这个系统通常工作,考虑下面的代码(写作样例不是从程序):

Im trying to compare the address of two functions for equality. Type of my stored function is known. This system normally works, consider the following code (written as sample not from the program):

virtual bool compare(void *fn2) {
  void (*fn)(int);

  if(fn==fn2)
     return true;
}

但是当考虑类函数时,同样的方法不起作用。 / p>

However when class functions came into consideration the same method doesn't work.

virtual bool compare(void *fn2) {
  void(__thiscall myclass::*fn)(int);
  void *fn2;

  if(fn==fn2)  //error C2440 type cast: cannot convert void* to void(__thiscall...
     return true;
}

这些函数覆盖了一个类似于以下内容的公共基类的纯虚函数:

These functions override a common base class' pure virtual function similar to following:

virtual bool compare(void*) = 0;

因为我不能在虚函数中使用模板<>我没有选项。有没有办法(无论如何)统一类函数和常规函数?

Since I cannot use template<> in virtual functions I am out of options. Is there a way (anyway) to unify class functions and regular functions?

提前,
Cem

Thanks in advance, Cem

推荐答案

Posix需要将函数指针转换为 void * 。标准C ++不支持。

Posix requires the ability to convert function pointers to void*. Standard C++ does not support it.

成员函数指针不是普通意义上的指针,它们更像偏移量非虚拟成员函数)。

Member function pointers are not pointers in the ordinary sense, they're more like offsets (even for a non-virtual member function).

对于比较显示的两个实现都会有未定义行为,即使比较和casts是有效的,因为它们在指针不比较相等的情况下不能返回任何东西。而不是 if(blah == bag){return true; } 只需执行 return(blah == bah);

Both implementations you show for compare would have Undefined Behavior even if the comparisions and casts were valid, because they fail to return anything in the case where the pointers don't compare equal. Instead of if(blah == bag){ return true; } just do return (blah == bah);.

从丢弃必要的类型信息。这通常不是一个好主意。

The problems stem from casting away necessary type information. That's generally not a good idea. Why are you casting away the type information that you need?

解决方法:(1)不要丢弃必要的类型信息, 2)重新设计以摆脱比较函数。还要注意到罗杰·帕特的评论,似乎你问一个特定的尝试解决方案,而不是问题。有什么问题?

Solution: (1) don't cast away necessary type information, and (2) redesign to get rid of that compare function. Also take note of Roger Pate's comment that it seems you're asking about a particular attempted solution rather then the problem. What is the problem?

hth。,

这篇关于将类函数指针转换为void *,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆