C++比较成员函数指针
在C++中,是否可以为指向成员函数的指针定义排序顺序?看来运营商<未定义。另外,强制转换为 void* 也是非法的。
class A
{
public:
void Test1(){}
void Test2(){}
};
int main()
{
void (A::* const one)() = &A::Test1;
void (A::* const two)() = &A::Test2;
bool equal = one == two; //Equality works fine.
bool less = one < two; //Less than doesn't.
return 0;
}
谢谢!
In C++, is it possible to define a sort order for pointers to member functions? It seems that the operator< is undefined. Also, it's illegal to cast to void*.
class A
{
public:
void Test1(){}
void Test2(){}
};
int main()
{
void (A::* const one)() = &A::Test1;
void (A::* const two)() = &A::Test2;
bool equal = one == two; //Equality works fine.
bool less = one < two; //Less than doesn't.
return 0;
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
函数指针在 C++ 中不具有相关可比性。支持相等比较,但至少一个指针实际指向虚拟成员函数的情况除外(在这种情况下结果未指定)。
当然,您始终可以通过实现比较谓词并显式比较指针来引入排序(尽管看起来不太优雅,因为您只能使用相等比较)。其他可能的解决方案将跨越各种特定于实现的“黑客”领域。
Function pointers are not relationally comparable in C++. Equality comparisons are supported, except for situations when at least one of the pointers actually points to a virtual member function (in which case the result is unspecified).
Of course, you can always introduce an ordering by implementing a comparison predicate and comparing the pointers explicitly (won't look too elegant though, since you can only use equality comparisons). Other possible solutions would cross into the territory of the various implementation-specific "hacks".
成员函数指针不是实际的指针。您应该将它们视为不透明的结构。方法指针包含什么:
如果您可以将其强制转换为 void* (您不能),那么您将拥有的只是结构体的指针,而不是指向代码的指针。这就是为什么operator<()也是未定义的,因为结构体指针的值恰好位于内存中的位置。
除此之外,您还根据什么进行排序?
Member function pointers are not actual pointers. You should look at them as opaque structs. What does a method pointer contain:
If you could cast this to void* (you can't) all you would have is a pointer the the struct, not a pointer to code. That's why operator<() is undefined as well since the value of the struct's pointer is just where ever it happens to be in memory.
In addition to that, what are you sorting by?