Somnium

C++: Static Array Wrapper Using Variadic Templates

⇜ back to C++

A while ago I needed a wrapper class for static arrays (C-style arrays). For convience I wanted to construct an array by passing the elements to the constructor. This can be done with std::initializer_list, but I wasn't able to use the STL.

With variadic templates is it possible though (thanks Stack Overflow). Errors are not handled in the example below. You can use something like the expected<T,E> monad or exceptions.

#include <stdio.h>
#include <inttypes.h>

template <typename T, size_t Capacity> class Array {
private:
  T _data[Capacity];
  size_t _size;

public:
  const size_t capacity = Capacity;

  template <typename... Args>
  constexpr Array(const Args &... args)
      : _data{static_cast<T>(args)...}, _size{sizeof...(args)} {}

  size_t size() const { return _size; }

  T get(size_t index) const {
    // TODO: Error reporting.
    return _data[index];
  }

  void set(size_t index, T value) {
    if (index > _size) {
      return; // TODO: Error reporting.
    }
    _data[index] = value;
  }

  void append(T value) {
    if (_size == capacity) {
      return; // TODO: Error reporting.
    }
    _data[_size++] = value;
  }
};

int main() {
  auto a = Array<uint64_t, 16>(1, 2);

  printf("Element 0: %lu\n", a.get(0));
  printf("Element 1: %lu\n", a.get(1));

  a.append(5);
  printf("Element 2: %lu\n", a.get(2));

  printf("Size: %zu\n", a.size());
  printf("Capacity: %zu\n", a.capacity);

  return 0;
}

References