Array.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifndef CORE_ARRAY_H
  2. #define CORE_ARRAY_H
  3. #include "utils/ArrayString.h"
  4. namespace Core {
  5. template<typename T, int N>
  6. class Array final {
  7. static_assert(N > 0, "Array size must be positive");
  8. T data[static_cast<unsigned int>(N)];
  9. public:
  10. Array() = default;
  11. Array(const T& t) {
  12. fill(t);
  13. }
  14. void fill(const T& t) {
  15. for(int i = 0; i < N; i++) {
  16. data[i] = t;
  17. }
  18. }
  19. T& operator[](int index) {
  20. return data[index];
  21. }
  22. const T& operator[](int index) const {
  23. return data[index];
  24. }
  25. T* begin() {
  26. return data;
  27. }
  28. T* end() {
  29. return data + N;
  30. }
  31. const T* begin() const {
  32. return data;
  33. }
  34. const T* end() const {
  35. return data + N;
  36. }
  37. constexpr int getLength() const {
  38. return N;
  39. }
  40. // returns true on error
  41. template<int L>
  42. check_return bool toString(ArrayString<L>& s) const {
  43. if(s.append("[")) {
  44. return true;
  45. }
  46. for(int i = 0; i < N - 1; i++) {
  47. if(s.append(data[i]) || s.append(", ")) {
  48. return true;
  49. }
  50. }
  51. if(N > 0 && s.append(data[N - 1])) {
  52. return true;
  53. }
  54. return s.append("]");
  55. }
  56. };
  57. }
  58. #endif