dimanche 29 mai 2016

What is the "best" way to overload arithmetic operators in modern C++?

I want to implement a kind of "number-like" mathematical objects (say, elements in a group or a ring) in C++. I'm sure that I'm not the only one dealing with this problem, so there may be abundant amount of discussions about what is the "best" way of overloading arithmetic operators. However, I couldn't find satisfactory answers (although maybe I was too lazy to googling more).

Let's say I want to overload the operator "+" for a class A. The problem is, there are too many different overloads I can think of:

  1. operator+(const A& x, const A& y)
  2. operator+(const A& x, A&& y)
  3. operator+(A&& x, const A& y)
  4. operator+(A&& x, A&& y)
  5. A::operator+=(const A& y) &
  6. A::operator+=(const A& y) &&
  7. A::operator+=(A&& y) &
  8. A::operator+=(A&& y) &&

First question. Do all of these overloads necessary to make operations on instances of A as efficient as, and as much as "being like primitive types" as possible? I think for "ordinary" cases, rvalue-qualified A::operator+= need not (or should not) be overloaded. Is it right? I think all of 1-4 are necessary. For example, for the case 3, since x is being moved, we do not need to allocate a new space to hold the return value, and we can safely reuse the allocation storage reserved for x. Is it right?

Second question. I think all of these overloads may share a lot of codes for most of this kind of cases. How can I minimize the code duplication without sacrificing performance/etc.? Is there any special techniques/idioms to do this? I prefer general and extensible methods, if exist.

Aucun commentaire:

Enregistrer un commentaire