C ++比较成员函数指针 [英] C++ Comparing Member Function Pointers

查看:117
本文介绍了C ++比较成员函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,是否可以为成员函数的指针定义排序顺序?看来操作员<未定义.另外,将其强制转换为无效*是非法的.

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;
}

谢谢!

推荐答案

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

当然,您总是可以通过实现比较谓词并显式比较指针来引入顺序(尽管看起来不太优雅,因为您只能使用相等比较).其他可能的解决方案将进入各种特定于实现的"hacks"领域.

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".

这篇关于C ++比较成员函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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