Last active
September 23, 2019 16:00
-
-
Save johnfredcee/ed827679502e045638a95d157f35958f to your computer and use it in GitHub Desktop.
C++17 generic vector class
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
#include <cstddef> | |
#include <array> | |
#include <tuple> | |
template <typename T, std::size_t N> | |
struct Vec | |
{ | |
std::array<T, N> m; | |
using element_type = T; | |
static constexpr std::size_t dim = N; | |
Vec() | |
{ | |
} | |
Vec(float x) : m{x} | |
{ | |
} | |
Vec(T x, T y) : m{x,y} | |
{ | |
} | |
Vec(T x, T y, T z) : m{x, y, z} | |
{ | |
} | |
Vec(T x, T y, T z, T w) : m{x, y, z, w} | |
{ | |
} | |
Vec(std::array<T,N> other) : m(other) | |
{ | |
} | |
}; | |
template<typename T, std::size_t N> | |
Vec<T,N> operator+(Vec<T,N> a, Vec<T,N> b) | |
{ | |
Vec<T,N> result; | |
for(std::size_t i = 0; i < N; ++i) | |
{ | |
result.m[i] = a.m[i] + b.m[i]; | |
} | |
return result; | |
} | |
template<typename T>Vec(T x) -> Vec<T,1>; | |
template<typename T>Vec(T x, T y) -> Vec<T,2>; | |
template<typename T>Vec(T x, T y, T z) -> Vec<T,3>; | |
template<typename T>Vec(T x, T y, T z, T w) -> Vec<T,4>; | |
template <typename T> using Vec2 = Vec<T, 2>; | |
template <typename T> using Vec3 = Vec<T, 3>; | |
template <typename T> using Vec4 = Vec<T, 4>; | |
Vec<float, 3> add(float q) { | |
Vec a{0.0f, 1.0f, 2.0f}; | |
Vec b{5.0f, 2.0f, 1.0f}; | |
a.m[0] = q; | |
Vec c = a + b; | |
return c; | |
} | |
float vecadd() | |
{ | |
float in = 2.6f; | |
Vec d = add(2.6f); | |
return d.m[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment