summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorNao Pross <naopross@thearcway.org>2018-12-10 15:10:55 +0100
committerNao Pross <naopross@thearcway.org>2018-12-10 15:10:55 +0100
commitc2ec583c30cc95dd681dbb0c9fc5a46572913e22 (patch)
tree973ded7a18a2e63e4998ac30d384478f0702af20
parentImplement cross product for vec2 and vec3 (diff)
downloadcplusplus-c2ec583c30cc95dd681dbb0c9fc5a46572913e22.tar.gz
cplusplus-c2ec583c30cc95dd681dbb0c9fc5a46572913e22.zip
Update makefile ad update basic_vec to allow abstract algebraic structures
Unfortunately this requires C++17 as `static constexpr` members have an undefined behaviour before this version.
-rw-r--r--vector/makefile4
-rw-r--r--vector/vector.cpp13
2 files changed, 11 insertions, 6 deletions
diff --git a/vector/makefile b/vector/makefile
index 1303aa3..31136ea 100644
--- a/vector/makefile
+++ b/vector/makefile
@@ -2,8 +2,8 @@ CC := gcc
CARGS := -Wall -Werror -I.
LDARGS := -lm
-CPPC := g++
-CPPARGS := -Wall -I.
+CPPC := g++-8
+CPPARGS := -Wall -I. -std=c++17
all: vector.pdf c_build/vector cpp_build/vector
diff --git a/vector/vector.cpp b/vector/vector.cpp
index 9e0ca6c..d5f0c36 100644
--- a/vector/vector.cpp
+++ b/vector/vector.cpp
@@ -6,10 +6,15 @@
#include <initializer_list>
#include <algorithm>
+
template<typename T, std::size_t d>
struct basic_vec : public std::array<T, d> {
static constexpr std::size_t dimensions = d;
+ static constexpr T null_element = static_cast<T>(0);
+ static constexpr T unit_element = static_cast<T>(1);
+ static constexpr T unit_additive_inverse_element = static_cast<T>(-1);
+
basic_vec();
basic_vec(const std::initializer_list<T> l);
template<std::size_t n> basic_vec(const basic_vec<T, n>& other);
@@ -19,7 +24,7 @@ struct basic_vec : public std::array<T, d> {
template<typename T, std::size_t d>
basic_vec<T, d>::basic_vec() : std::array<T, d>() {
- this->fill(static_cast<T>(0));
+ this->fill(basic_vec<T,d>::null_element);
}
template<typename T, std::size_t d>
@@ -44,7 +49,7 @@ basic_vec<T, d>::basic_vec(const basic_vec<T, n>& other) {
template<typename T, std::size_t d>
T basic_vec<T, d>::length() const {
- T res = static_cast<T>(0);
+ T res = basic_vec<T, d>::null_element;
for (const T& val : *this) {
res += val * val;
}
@@ -77,12 +82,12 @@ basic_vec<T, d> operator*(const T& rhs, const basic_vec<T, d>& lhs) {
template<typename T, std::size_t d>
basic_vec<T, d> operator-(const basic_vec<T, d>& rhs, const basic_vec<T, d>& lhs) {
- return rhs + static_cast<T>(-1) * lhs;
+ return rhs + basic_vec<T, d>::unit_additive_inverse_element * lhs;
}
template<typename T, std::size_t d>
T operator*(const basic_vec<T, d>& rhs, const basic_vec<T, d>& lhs) {
- T res = static_cast<T>(0);
+ T res = basic_vec<T, d>::null_element;
for (std::size_t i = 0; i < d; i++) {
res += rhs[i] * lhs[i];
}