Michael M.
Michael M.

Reputation: 2584

Overload operator in C++

Let say I have a class :

class MyIntegers
{
public:
  MyIntegers(int sz); //allocate sz integers in _Data and do some expensive stuff
  ~MyIntegers();      //free array

  int* _Data;
}

And this small piece of code :

int sz = 10;
MyIntegers a(sz), b(sz), c(sz);

for (int i=0; i<sz; i++)
{
  c._Data[i] = a._Data[i] + b._Data[i];
}

Is it possible to overload a ternary operator+ to replace the loop with c=a+b without create a temporary object ?

Overload the operator= and operator+= and write c=a; c+=b; to avoid the creation of a temporary object is not acceptable in my case.

Upvotes: 1

Views: 142

Answers (1)

dhavenith
dhavenith

Reputation: 2048

What you're looking for is called expression templates where basically an expression a+b does not lead to calculation of the result, but instead returns a 'proxy' object where the operation (+ in this case) is encoded in the type. Typically when you need the results, for instance when assigning to a variable, the operations that were encoded in the proxy type are used to do the actual calculation.

With C++11s move assignment operators there is less need for expression templates to optimize simple expressions with only one temporary (because that temporary will be moved to the final result), but it is still a technique to avoid big temporaries.

Upvotes: 1

Related Questions