On 07.01.18 17.33, Stefan Ram wrote:
> For a class, Herb Sutter once recommended to write
>
> inline pair operator +( pair result, pair const & other )
> { result += other; return result; }
Whether this is efficient or not depends. If the component types are
rather complex and if you use C++11 or above I would /not/ recommend
this. Copying could be expensive. And in contrast to the returned value
RVO and move semantics are not possible for the parameters.
Furthermore I dislike asymmetric definitions of symmetric operators.
Typically I would expect something like
inline friend pair operator +( pair const& l, pair const& r )
{ return pair(l.x + r.x, l.y + r.y); }
within the class. The "friend" will automatically create a free function
instead of a class member. This is common practice.
> outside of the class specifier and then in the class specifier:
>
> pair & operator +=( const pair & o )
> { x += o.x; y += o.y; return *this; }
Just fine.
> . So, now I want to implement
>
> inline bool operator ==( const pair & l, const pair & r )
>
> outside of the class specifier (as I believe it should
> be). Should I now write
>
> l.x == r.x && l.y == r.y
>
> into the definition of »operator ==« and add it as a friend
> to the class (»x« and »y« are private) or should I rather write
>
> inline bool operator ==( const pair & l, const pair & r )
> { return l.equals( r ); }
>
> and add a function
>
> bool equals( const pair & other )const
> { return this->x == other.x && this->y == other.y; }
>
> within the class specifier?
This is an option. But I would recommend the Java like, asymmetric
equals method only if you really need it.
Otherwise I recommend the same procedure as for operator+:
inline friend bool operator ==( const pair & l, const pair & r )
{ return l.x == r.x && l.y == r.y; }
Marcel