fork download
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. template<typename T, size_t L, size_t H>
  5. class Array
  6. {
  7. public:
  8. static_assert(H >= L);
  9. static const size_t Low = L;
  10. static const size_t High = H;
  11. static const size_t Length = (H - L + 1);
  12.  
  13. // stuff ...
  14.  
  15. Array() = default;
  16.  
  17. template<size_t Lb, size_t Hb>
  18. Array(const Array<T, Lb, Hb> &src)
  19. {
  20. static_assert(Length == Array<T, Lb, Hb>::Length);
  21. std::copy_n(src.actualArray, Length, actualArray);
  22. }
  23.  
  24. // just to show that you don't need an offset member...
  25.  
  26. T& operator[](size_t idx)
  27. {
  28. return actualArray[idx - L];
  29. }
  30.  
  31. T operator[](size_t idx) const
  32. {
  33. return actualArray[idx - L];
  34. }
  35.  
  36. template<typename, size_t, size_t>
  37. friend class Array;
  38.  
  39. private:
  40. T actualArray[Length];
  41. };
  42.  
  43. template<typename T, size_t L, size_t H>
  44. void printArray(const Array<T, L, H> &arr)
  45. {
  46. for (size_t idx = arr.Low; idx <= arr.High; ++idx)
  47. std::cout << arr[idx] << std::endl;
  48. }
  49.  
  50. int main()
  51. {
  52. Array<int, 0, 2> arr1;
  53. arr1[0] = 1;
  54. arr1[1] = 2;
  55. arr1[2] = 3;
  56. printArray(arr1);
  57.  
  58. std::cout << std::endl;
  59.  
  60. Array<int, 5, 7> arr2;
  61. arr2 = arr1;
  62. printArray(arr2);
  63.  
  64. return 0;
  65. }
Success #stdin #stdout 0s 4528KB
stdin
Standard input is empty
stdout
1
2
3

1
2
3