Created
April 27, 2021 21:56
-
-
Save barafael/37378e3bb1d2a05876f61c99a802c998 to your computer and use it in GitHub Desktop.
A constant size vector type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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