fork download
  1. #include <algorithm>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. template <class T, int s>
  7. class myArrayImpl {
  8. public:
  9. T* data;
  10. T& operator[](int i){return data[i];}
  11. const T& operator[](int i) const {return data[i];}
  12. myArrayImpl(){
  13. data=new T[s]();
  14. }
  15. myArrayImpl(const myArrayImpl & other){
  16. data=new T[s];
  17. copy(other.data,other.data+s,data);
  18. }
  19. myArrayImpl& operator=(const myArrayImpl& other){
  20. T* olddata = data;
  21. data=new T[s];
  22. copy(other.data,other.data+s,data);
  23. delete [] olddata;
  24. return *this;
  25. }
  26. ~myArrayImpl(){delete [] data;}
  27. };
  28.  
  29. template <class T, int s>
  30. class myArray : private myArrayImpl<T,s> {
  31. typedef myArrayImpl<T,s> Impl;
  32. public:
  33. using Impl::operator[];
  34. myArray() : Impl() {}
  35. typedef T value_type; // !!!
  36. explicit myArray(const value_type& value) {
  37. fill(this->data, this->data + s, value);
  38. }
  39. void setAll(const value_type& value) {
  40. fill(this->data, this->data + s, value);
  41. }
  42. };
  43.  
  44. template <class T, int s1, int s2>
  45. class myArray<myArray<T,s2>,s1> : private myArrayImpl<myArray<T,s2>,s1> {
  46. typedef myArrayImpl<myArray<T,s2>,s1> Impl;
  47. public:
  48. using Impl::operator[];
  49. myArray() : Impl() {}
  50. typedef typename myArray<T,s2>::value_type value_type; // !!!
  51. explicit myArray(const value_type& value) {
  52. setAll(value);
  53. }
  54. void setAll(const value_type& value) {
  55. for_each(this->data, this->data + s1, [value](myArray<T,s2>& v) { v.setAll(value); });
  56. }
  57. };
  58.  
  59. int main() {
  60. myArray<myArray<myArray<int,7>,8>,9> a(7);
  61. std::cout << a[0][0][0] << std::endl;
  62. std::cout << a[8][7][6] << std::endl;
  63. }
Success #stdin #stdout 0s 3016KB
stdin
Standard input is empty
stdout
7
7