【问题标题】:Why do I have to overload operator== in POD types?为什么我必须在 POD 类型中重载 operator==?
【发布时间】:2012-04-09 01:43:06
【问题描述】:

我有一个这样定义的结构:

struct Vec3 {
float x, y, z;
}

当我尝试在 std::vector<Vec3> 上使用 std::unique 时,遇到了这个错误:

描述资源路径位置类型 '_first._gnu_cxx::__normal_iterator<_iterator _container>::operator* with _Iterator = Vec3*, _Container = std::vector > == _next._gnu_cxx::__normal_iterator<_iterator _container>::operator* with _Iterator = Vec3*, _Container = std::vector >' ModelConverter line 4351,外部位置:/usr/include/c++/4.4 .6/bits/stl_algo.h C/C++问题

我理解编译器在 in 等式运算符和其他方面的必要性(在这种情况下,* 几乎肯定不是我的意思),但这是一个政策问题,还是有我不知道的技术原因?有一个默认的赋值运算符,那为什么没有默认的相等运算符呢?

【问题讨论】:

  • 因为在平等方面没有适当的“默认行为”。
  • @EtiennedeMartel:可能会有。例如,在 Ada 中,记录的相等性是根据组件的相等性来定义的。
  • 平等和不平等同样容易定义。
  • 你可以使用内存比较memcmp like (memcmp(&amp;veca, &amp;vecb, sizeof(Vec3)) == 0)来检查veca == vecb是否存在

标签: c++ operator-overloading


【解决方案1】:

C++20 增加了这个能力:

struct Vec3 {
    float x, y, z;
    auto operator<=>(const Vec3&) const = default;
    bool operator==(X const&) const = default;
}

目前仅在 GCC 和 clang trunk 中实现。请注意,当前默认 operator&lt;=&gt; 等同于默认 operator==,但是有一个 accepted proposal to remove this。该提案建议默认 operator&lt;=&gt; 也意味着(不等同于现在)默认 operator== 作为扩展。

Microsoft 在https://devblogs.microsoft.com/cppblog/simplify-your-code-with-rocket-science-c20s-spaceship-operator/ 上有关于此功能的文档。

【讨论】:

    【解决方案2】:

    为什么必须提供operator==的问题与为什么必须提供一些比较功能的问题不同。

    关于后者,您需要提供比较逻辑的原因是元素方面的相等性很少合适。例如,考虑一个带有 char 数组的 POD 结构。如果它被用来保存一个以零结尾的字符串,那么两个这样的结构可以在二进制级别比较不相等(由于字符串中零字节之后的任意内容)但在逻辑上是等价的。

    此外,这里的其他答案提到的所有 C++ 级别的复杂性,例如多态相等特别棘手的一个(你真的不希望编译器选择!)。

    所以,基本上,根本没有好的默认选择,所以选择是你的。

    关于前一个问题,也就是你的字面意思,为什么你必须提供operator==?

    如果您定义了operator&lt; 和operator==,那么命名空间std::rel_ops 中的运算符定义可以为您填写其余部分。大概需要operator== 的原因是,根据operator&lt; 来实现它会不必要地低效(然后需要两次 比较)。然而,选择这两个运算符作为基础是完全令人困惑的,因为它使用户代码冗长而复杂,并且在某些情况下效率远远低于可能!

    恕我直言,比较运算符的最佳基础是三值 compare 函数,例如 std::string::compare。

    给定一个成员函数变体comparedTo,然后您可以使用如下所示的 Curiously Recurring Template Pattern 类来提供全套运算符:

    template< class Derived >
    class ComparisionOps
    {
    public:
        friend int compare( Derived const a, Derived const& b )
        {
            return a.comparedTo( b );
        }
    
        friend bool operator<( Derived const a, Derived const b )
        {
            return (compare( a, b ) < 0);
        }
    
        friend bool operator<=( Derived const a, Derived const b )
        {
            return (compare( a, b ) <= 0);
        }
    
        friend bool operator==( Derived const a, Derived const b )
        {
            return (compare( a, b ) == 0);
        }
    
        friend bool operator>=( Derived const a, Derived const b )
        {
            return (compare( a, b ) >= 0);
        }
    
        friend bool operator>( Derived const a, Derived const b )
        {
            return (compare( a, b ) > 0);
        }
    
        friend bool operator!=( Derived const a, Derived const b )
        {
            return (compare( a, b ) != 0);
        }
    };
    

    其中compare 是一个重载函数,例如像这样:

    template< class Type >
    inline bool lt( Type const& a, Type const& b )
    {
        return std::less<Type>()( a, b );
    }
    
    template< class Type >
    inline bool eq( Type const& a, Type const& b )
    {
        return std::equal_to<Type>()( a, b );
    }
    
    template< class Type >
    inline int compare( Type const& a, Type const b )
    {
        return (lt( a, b )? -1 : eq( a, b )? 0 : +1);
    }
    
    template< class Char >
    inline int compare( basic_string<Char> const& a, basic_string<Char> const& b )
    {
        return a.compare( b );
    }
    
    template< class Char >
    inline int compareCStrings( Char const a[], Char const b[] )
    {
        typedef char_traits<Char>   Traits;
    
        Size const  aLen    = Traits::length( a );
        Size const  bLen    = Traits::length( b );
    
        // Since there can be negative Char values, cannot rely on comparision stopping
        // at zero termination (this can probably be much optimized at assembly level):
        int const way = Traits::compare( a, b, min( aLen, bLen ) );
        return (way == 0? compare( aLen, bLen ) : way);
    }
    
    inline int compare( char const a[], char const b[] )
    {
        return compareCStrings( a, b );
    }
    
    inline int compare( wchar_t const a[], wchar_t const b[] )
    {
        return compareCStrings( a, b );
    }
    

    现在,这就是机器。将它应用到您的班级会是什么样子……

    struct Vec3
    {
        float x, y, z;
    };
    

    ?

    这很简单:

    struct Vec3
        : public ComparisionOps<Vec3>
    {
        float x, y, z;
    
        int comparedTo( Vec3 const& other ) const
        {
            if( int c = compare( x, other.x ) ) { return c; }
            if( int c = compare( y, other.y ) ) { return c; }
            if( int c = compare( z, other.z ) ) { return c; }
            return 0;   // Equal.
        }
    };
    

    免责声明:未经过充分测试的代码... :-)

    【讨论】:

    • 这是一个很好的答案。 CRTP 是我希望我了解更多的东西,感谢您在上下文中展示它!我也从来没有听说过std::rel_ops,所以我得去看看。
    【解决方案3】:

    没有技术原因。学究式地,你可能会说这是因为 C 不允许你将两个结构与== 进行比较,这是一个很好的理由;当您使用 C++ 时,这种行为切换并不明显。 (据推测,C 不支持的原因是字段比较可能适用于 一些 结构,但绝对不是全部。)

    仅从 C++ 的角度来看,如果您有一个私有字段怎么办?默认的== 在技术上公开了该字段(间接地,但仍然)。那么如果没有私有或受保护的数据成员,编译器是否只会生成operator==?

    此外,有些类没有合理的相等定义(空类,不建模状态但缓存它的类等),或者默认相等检查可能非常令人困惑(包装指针的类) .

    然后是继承。在继承的情况下决定为operator== 做什么是复杂的,编译器很容易做出错误的决定。 (例如,如果这是 C++ 所做的,我们可能会问为什么== 在测试两个对象之间的相等性时总是成功,这两个对象都是抽象基类的后代并与它的引用一起使用。)

    基本上,这是一个棘手的问题,即使考虑到您可以覆盖编译器决定的任何内容,编译器也不要介入它会更安全。

    【讨论】:

    • 谢谢,我不知道 C 的那个方面,并且可能有一些类看起来像简单的聚合容器,但没有相等的概念是一个好的。跨度>
    【解决方案4】:

    您希望等式运算是什么?所有领域都一样吗?它不会为你做出决定。

    【讨论】:

    • 在这种情况下,我定义的operator== 就是这样做的。我可以看到您可能希望比较器在哪里增加复杂性,但我想不出两个具有完全相同数据的structs 会不相等的情况。你能想出一个例子吗?
    • 这与“默认的复制构造函数或赋值运算符是什么?”是同一个问题
    • K.G.:例如,如果两个对象具有相同的标识 (=address),则它们是相等的
    • @K.G. - 我并不是说我不认为应该定义一个默认值,但这就是它的定义方式。卡罗利的例子很现实
    • @KarolyHorvath 谢谢,这是我没有想到的。
    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2015-04-04
    • 2011-04-23
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多