List.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #ifndef LIST_H
  2. #define LIST_H
  3. #include <utility>
  4. template<typename T, int N>
  5. class List final {
  6. char data[sizeof (T) * N];
  7. int index = 0;
  8. void copy(const List& other) {
  9. for(int i = 0; i < other.index; i++) {
  10. add(other[i]);
  11. }
  12. }
  13. void move(List&& other) {
  14. for(int i = 0; i < other.index; i++) {
  15. add(std::move(other[i]));
  16. }
  17. }
  18. public:
  19. List() = default;
  20. void clear() {
  21. for(int i = 0; i < index; i++) {
  22. (*this)[i].~T();
  23. }
  24. index = 0;
  25. }
  26. ~List() {
  27. clear();
  28. }
  29. List(const List& other) : index(0) {
  30. copy(other);
  31. }
  32. List& operator=(const List& other) {
  33. if(&other != this) {
  34. clear();
  35. copy(other);
  36. }
  37. return *this;
  38. }
  39. List(List&& other) : index(0) {
  40. move(std::move(other));
  41. other.clear();
  42. }
  43. List& operator=(List&& other) {
  44. if(&other != this) {
  45. clear();
  46. move(std::move(other));
  47. other.clear();
  48. }
  49. return *this;
  50. }
  51. T* begin() {
  52. return reinterpret_cast<T*> (data);
  53. }
  54. T* end() {
  55. return reinterpret_cast<T*> (data) + index;
  56. }
  57. const T* begin() const {
  58. return reinterpret_cast<const T*> (data);
  59. }
  60. const T* end() const {
  61. return reinterpret_cast<const T*> (data) + index;
  62. }
  63. void add(const T& t) {
  64. if(index >= N) {
  65. return;
  66. }
  67. new (end()) T(t);
  68. index++;
  69. }
  70. void add(T&& t) {
  71. if(index >= N) {
  72. return;
  73. }
  74. new (end()) T(std::move(t));
  75. index++;
  76. }
  77. template<typename... Args>
  78. void add(Args&&... args) {
  79. if(index >= N) {
  80. return;
  81. }
  82. new (end()) T(args...);
  83. index++;
  84. }
  85. T& operator[](int index) {
  86. return begin()[index];
  87. }
  88. const T& operator[](int index) const {
  89. return begin()[index];
  90. }
  91. int getLength() const {
  92. return index;
  93. }
  94. };
  95. #endif