user2138149
user2138149

Reputation: 16559

Implementation of comparison operators, `operator<`, as member function or external function

So according to this question it is preferable to implement many operators as external functions rather than member functions. So far I gather that this is because "it makes code more symetrical"... although I haven't yet figured out why that might be advantageous other than it looks nice. I'm guessing when using templates, it means you can get away without writing lots of code?

Anyway, what I wanted to know is: Is it ever appropriate to implement something like operator< as a member function? Or are there no advantages to this?

Reason I ask is because I would never have thought to implement such an operator as an external function. In many examples I have seen before, operators are always implemented as member functions. Is implementing them externally a recent idea which is now considered to be "better"?

(PS: Would someone please clarify why external implementations are the way to go?)

Edit: Actually I have found this link - people seem to disagree about what the best methods is and why.

Upvotes: 0

Views: 354

Answers (1)

The reason that operators are commonly preferred as free functions is that they become type-wise symmetrical. This is more important, or actually important at all, when the type has implicit conversions.

Consider for example an optional type that resembles std::optional from the upcoming C++14 standard, that is implicitly convertible from template argument type, and considering comparing the optional object with the nested type (and imagine that you don't want to implement all of the operator< variants, which the standard actually does):

// optional is like std::optional, implements operator<(optional<T>,optional<T>)
// but we did not care to provide operator<(T,optional<T>) and operator<(optional<T>,T)
optional<int> oi = 1;      // good, we can implicitly convert
if (oi < 10) {             // and we can compare
...
} else if (0 < oi) {       // we also want to compare this way!
...
}

Now if operator< is implemented as a free function, then the code above will work. If it is implemented as a member function the second if will fail, as no conversions can be applied to the left hand side prior to calling a member function.

Is it ever appropriate to implement something like operator< as a member function? Or are there no advantages to this?

There are cases where it won't matter, but it won't provide advantages either. Although this statement is not fully true... lookup is different for the operator being implemented in one way or another, but in the general case it won't matter. If you are in a situation where it matters, then there are deeper issues to care about.

Upvotes: 3

Related Questions