opEquals()

Let’s discuss how opEquals() is used for equality comparisons.

We'll cover the following

opEquals() for equality comparisons

This member function defines the behaviors of the == and the != operators.

The return type of opEquals is bool. For structs, the parameter of opEquals can be defined as in. However, for speed efficiency, opEquals can be defined as a template that takes auto ref const (Also, note the empty template parentheses below.):

bool opEquals()(auto ref const TimeOfDay rhs) const {
// ...
}

As we know, auto ref allows lvalues to be passed by reference and rvalues by copy. However, since rvalues are not copied, rather moved, the signature above is efficient for both lvalues and rvalues.

To reduce confusion, opEquals and opCmp must work consistently. For the two objects that opEquals returns true, opCmp must return zero.

Get hands-on with 1200+ tech skills courses.