fork download
  1. #include <utility> // move
  2. #include <iostream>
  3.  
  4. using std::move;
  5. using std::ostream;
  6.  
  7. struct Matrix {
  8. int d; /* = 0, not yet implemented in gcc-4.7.0 */
  9. Matrix(int e) : d{e} {}
  10.  
  11. // construction, copy, assign
  12. Matrix() = default;
  13. Matrix(const Matrix&) = default;
  14. Matrix& operator=(const Matrix&) = default;
  15.  
  16. // move, move-assign (no no magic in this example)
  17. Matrix(Matrix&&) = default;
  18. //Matrix& operator=(Matrix&&) = default;
  19. Matrix& operator=(Matrix&& o) { swap(*this,o); return *this; };
  20.  
  21. // friendly STL helper
  22. friend void swap(Matrix& a, Matrix& b) /* noexcept */ { std::swap(a.d, b.d); }
  23.  
  24. // imm ops
  25. void operator+=(const Matrix& o) { d+=o.d; }
  26. void operator*=(const Matrix& o) { d*=o.d; }
  27.  
  28. // 2ary ops
  29. friend Matrix operator+(const Matrix &a, Matrix &&b ) { b+=a; return move(b); }
  30. friend Matrix operator+(Matrix &&a, const Matrix &b) { a+=b; return move(a); }
  31. friend Matrix operator+(const Matrix &a, Matrix v) { v+=a; return v; }
  32. friend Matrix operator+(Matrix &&a, Matrix &&b) { a+=b; return move(a); }
  33.  
  34. friend Matrix operator*(const Matrix &a, Matrix &&b ) { b*=a; return move(b); }
  35. friend Matrix operator*(Matrix &&a, const Matrix &b) { a*=b; return move(a); }
  36. friend Matrix operator*(const Matrix &a, Matrix v) { v*=a; return v; }
  37. friend Matrix operator*(Matrix &&a, Matrix &&b) { a*=b; return move(a); }
  38.  
  39. // demo helper
  40. friend ostream& operator<<(ostream&os, const Matrix& m)
  41. { return os << m.d; }
  42.  
  43. };
  44.  
  45.  
  46. int main()
  47. {
  48. Matrix a{2},b{3},c{4},d{5};
  49. Matrix x = a*b + c*d; // 2*3+4*5 = 6+20 = 26
  50.  
  51. std::cout << x << std::endl;
  52. }
  53.  
Success #stdin #stdout 0s 2828KB
stdin
Standard input is empty
stdout
26