Created
February 5, 2019 14:38
-
-
Save kvk1920/54c08af47e9cc013c95c9a20f984eda9 to your computer and use it in GitHub Desktop.
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
template <typename T, size_t D = 1, bool Owner = true> | |
class TMatrix | |
{ | |
public: | |
TMatrix(std::vector<size_t> n_) | |
: n(std::move(n_)) | |
{ | |
static_assert(Owner); | |
assert(n.size() == D - 1); | |
std::partial_sum(std::begin(n), std::end(n), std::begin(n)); | |
data = new T[n[D - 1]]; | |
} | |
~TMatrix() | |
{ | |
if constexpr (Owner) | |
Clear(); | |
} | |
void Clear() | |
{ | |
static_assert (Owner); | |
std::fill(n, 0); | |
delete [] data; | |
data = nullptr; | |
} | |
void Swap(TMatrix&& other) | |
{ | |
static_assert (Owner); | |
std::swap(other.data, data); | |
std::swap(other.n, n); | |
} | |
void Copy(const TMatrix& other) | |
{ | |
Clear(); | |
n = other.n; | |
data = new T[n[D - 1]]; | |
std::copy(other.data, other.data + n[D - 1], data); | |
} | |
TMatrix(const TMatrix& other) { Copy(other); } | |
TMatrix& operator=(const TMatrix& other) { Copy(other); return *this; } | |
TMatrix(TMatrix&& other) { Swap(other); } | |
TMatrix& operator=(TMatrix&& other) { Swap(other); return *this; }; | |
decltype(auto) operator[](size_t i) | |
{ | |
if constexpr (D == 1) return static_cast<T&>(data[i]); | |
else return TMatrix<T, D - 1, false>(n, data + i * n[D - 2]); | |
} | |
decltype(auto) operator[](size_t i) const | |
{ | |
if constexpr (D == 1) return static_cast<const T&>(data[i]); | |
else return | |
static_cast<const TMatrix<T, D - 1, false>>(TMatrix<T, D - 1, false>(n, data + i * n[D - 2])); | |
} | |
const auto& WatchD() const { return n; } | |
private: | |
TMatrix(const std::vector<size_t>& n_, | |
T* data_) | |
: n(n), data(data_) | |
{} | |
std::conditional_t<Owner, | |
std::vector<size_t>, const std::vector<size_t>&> | |
n; | |
std::conditional_t<Owner, | |
T*, T* const> data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment