fork download
  1. #include <vector>
  2. #include <utility>
  3. #include <iostream>
  4.  
  5. template <typename T>
  6. class Matrix {
  7.  
  8. private:
  9.  
  10. class Row {
  11. friend class Matrix;
  12.  
  13. public:
  14. T& operator[] (int j)&&
  15. {
  16. return matrix.mappedVector[i * matrix.n + j];
  17. }
  18. const T& operator[] (int j) const&&
  19. {
  20. return matrix.mappedVector[i * matrix.n + j];
  21. }
  22. private:
  23. int i;
  24. Matrix& matrix;
  25.  
  26. Row(int i, Matrix& matrix) : i(i), matrix(matrix) {
  27. std::cout << "int ctor" << std::endl;
  28. }
  29.  
  30. Row() {
  31. std::cout << "ctor" << std::endl;
  32. }
  33.  
  34. };
  35. public:
  36. Matrix() :
  37. m(0),
  38. n(0)
  39. {}
  40. explicit Matrix(size_t m, size_t n) : m(m), n(n), mappedVector(m* n){
  41. }
  42.  
  43.  
  44. Row operator[] (int i) {
  45. return Row(i, *this);
  46. }
  47.  
  48. const Row operator[] (int i) const {
  49. return Row(i, *this);
  50. }
  51.  
  52. private:
  53. size_t m;
  54. size_t n;
  55. std::vector<T> mappedVector;
  56. };
  57.  
  58. int main()
  59. {
  60. Matrix<int> matrix(2, 5);
  61. matrix[1][0] = 1;
  62.  
  63. auto autoRowProxy = matrix[1];
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 4396KB
stdin
Standard input is empty
stdout
int ctor
int ctor