Skip to content

Instantly share code, notes, and snippets.

@barafael
Created April 27, 2021 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barafael/37378e3bb1d2a05876f61c99a802c998 to your computer and use it in GitHub Desktop.
Save barafael/37378e3bb1d2a05876f61c99a802c998 to your computer and use it in GitHub Desktop.
A constant size vector type
#pragma once
#ifndef ARDUINO_AVR_UNO
#include <cstddef>
#endif
template<typename T, size_t SIZE>
class Vec {
public:
Vec(std::initializer_list<T> init) {
assert(init.size() == SIZE);
size_t i = 0;
for (auto elem: init) {
data[i++] = elem;
}
}
constexpr size_t size() {
return SIZE;
}
T &operator[](size_t index) {
return data[index];
}
const T &operator[](size_t index) const {
return data[index];
}
T *begin() {
return &data[0];
}
const T *begin() const {
return &data[0];
}
T *end() {
return &data[SIZE];
}
const T *end() const {
return &data[SIZE];
}
bool operator==(const Vec<T, SIZE> &rhs) const {
for (size_t i = 0; i < SIZE; i++) {
if ((*this)[i] != rhs[i]) {
return false;
}
}
return true;
}
bool operator!=(const Vec<T, SIZE> &rhs) const {
return !(*this == rhs);
}
private:
T data[SIZE] = {};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment