C++比较成员函数指针

发布于 2024-08-12 01:06:22 字数 402 浏览 4 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纸短情长 2024-08-19 01:06:22

函数指针在 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".

翻了热茶 2024-08-19 01:06:22

成员函数指针不是实际的指针。您应该将它们视为不透明的结构。方法指针包含什么:

 struct method_pointer {
     bool method_is_virtual;
     union {
         unsigned vtable_offset; // for a virtual function, need the vtable entry
         void* function_pointer; // otherwise need the pointer to the concrete method
     }
 };

如果您可以将其强制转换为 void* (您不能),那么您将拥有的只是结构体的指针,而不是指向代码的指针。这就是为什么operator<()也是未定义的,因为结构体指针的值恰好位于内存中的位置。

除此之外,您还根据什么进行排序?

Member function pointers are not actual pointers. You should look at them as opaque structs. What does a method pointer contain:

 struct method_pointer {
     bool method_is_virtual;
     union {
         unsigned vtable_offset; // for a virtual function, need the vtable entry
         void* function_pointer; // otherwise need the pointer to the concrete method
     }
 };

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文