为什么必须提供operator==的问题与为什么必须提供一些比较功能的问题不同。
关于后者,您需要提供比较逻辑的原因是元素方面的相等性很少合适。例如,考虑一个带有 char 数组的 POD 结构。如果它被用来保存一个以零结尾的字符串,那么两个这样的结构可以在二进制级别比较不相等(由于字符串中零字节之后的任意内容)但在逻辑上是等价的。
此外,这里的其他答案提到的所有 C++ 级别的复杂性,例如多态相等特别棘手的一个(你真的不希望编译器选择!)。
所以,基本上,根本没有好的默认选择,所以选择是你的。
关于前一个问题,也就是你的字面意思,为什么你必须提供operator==?
如果您定义了operator< 和operator==,那么命名空间std::rel_ops 中的运算符定义可以为您填写其余部分。大概需要operator== 的原因是,根据operator< 来实现它会不必要地低效(然后需要两次 比较)。然而,选择这两个运算符作为基础是完全令人困惑的,因为它使用户代码冗长而复杂,并且在某些情况下效率远远低于可能!
恕我直言,比较运算符的最佳基础是三值 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.
}
};
免责声明:未经过充分测试的代码... :-)