Skip to content

Instantly share code, notes, and snippets.

@drolevar
Created October 9, 2019 14:23
Show Gist options
  • Save drolevar/2c1549afb8868431e7857c551ed88857 to your computer and use it in GitHub Desktop.
Save drolevar/2c1549afb8868431e7857c551ed88857 to your computer and use it in GitHub Desktop.
vector-based matrix (rough concept)
//
// Created by Andrij Abyzov on 09.10.2019.
//
#ifndef MATRIX_H
#define MATRIX_H
#include <cstddef>
#include <utility>
#include <vector>
#include <functional>
#include <numeric>
template <typename T, size_t D>
class Matrix : public std::vector<T>
{
public:
template<typename... Args>
explicit Matrix(Args... args) : Matrix( {static_cast<size_t>(args)...} )
{
}
Matrix(std::initializer_list<size_t> dims) : dims_(dims)
{
size_t totalSize = std::accumulate(dims.begin(), dims.end(), 1, std::multiplies<>());
std::vector<T>::resize(totalSize);
}
template<typename... Args>
size_t index(Args&&... args)
{
static_assert(sizeof...(args) == D, "Matrix::index: invalid parameter count");
return indexInternal(std::forward<Args>(args)...);
}
template<typename... Args>
T& operator() (Args&&... args)
{
static_assert(sizeof...(args) == D, "Matrix::get: invalid parameter count");
return (*this)[indexInternal(std::forward<Args>(args)...)];
}
template<typename... Args>
T operator() (Args&&... args) const
{
static_assert(sizeof...(args) == D, "Matrix::get: invalid parameter count");
return (*this)[indexInternal(std::forward<Args>(args)...)];
}
template <size_t Dim>
size_t dim()
{
static_assert(Dim < D, "Matrix::dim: invalid dim index");
return dims_[Dim];
}
size_t dim(size_t dim)
{
return dims_[dim];
}
private:
template<typename... Args>
size_t indexInternal(size_t index1, Args&&... args)
{
size_t dim1 = dims_[sizeof...(args)];
return index1 + dim1 * indexInternal(std::forward<Args>(args)...) ;
};
size_t indexInternal(size_t index1)
{
return index1;
};
std::vector<size_t> dims_;
};
template <typename T, typename... Args>
auto CreateMatrix(Args&&... args)
{
return Matrix<T, sizeof...(args)>(std::forward<Args>(args)...);
}
#endif //MATRIX_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment