Skip to content

Commit ea4e27b

Browse files
committed
improved matrix class
1 parent 5454c43 commit ea4e27b

File tree

1 file changed

+38
-7
lines changed

1 file changed

+38
-7
lines changed

include/omath/Mat.hpp

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,15 @@ namespace omath
1717
{
1818
size_t rows, columns;
1919
};
20-
template<size_t Rows = 0, size_t Columns = 0, class Type = float>
20+
21+
enum class MatStoreType : uint8_t
22+
{
23+
ROW_MAJOR = 0,
24+
COLUMN_MAJOR
25+
};
26+
27+
template<size_t Rows = 0, size_t Columns = 0, class Type = float, MatStoreType StoreType = MatStoreType::ROW_MAJOR>
28+
requires (std::is_floating_point_v<Type> || std::is_integral_v<Type>)
2129
class Mat final
2230
{
2331
public:
@@ -26,8 +34,7 @@ namespace omath
2634
Clear();
2735
}
2836

29-
30-
constexpr Mat(const std::initializer_list<std::initializer_list<Type> > &rows)
37+
constexpr Mat(const std::initializer_list<std::initializer_list<Type>>& rows)
3138
{
3239
if (rows.size() != Rows)
3340
throw std::invalid_argument("Initializer list rows size does not match template parameter Rows");
@@ -42,18 +49,21 @@ namespace omath
4249
auto colIt = rowIt->begin();
4350
for (size_t j = 0; j < Columns; ++j, ++colIt)
4451
{
45-
At(i, j) = *colIt;
52+
At(i, j) = std::move(*colIt);
4653
}
4754
}
4855
}
4956

57+
constexpr explicit Mat(const Type* rawData)
58+
{
59+
std::copy_n(rawData, Rows * Columns, m_data.begin());
60+
}
5061

5162
constexpr Mat(const Mat &other) noexcept
5263
{
5364
m_data = other.m_data;
5465
}
5566

56-
5767
constexpr Mat(Mat &&other) noexcept
5868
{
5969
m_data = std::move(other.m_data);
@@ -77,13 +87,22 @@ namespace omath
7787
return {Rows, Columns};
7888
}
7989

80-
8190
[[nodiscard]] constexpr const Type &At(const size_t rowIndex, const size_t columnIndex) const
8291
{
8392
if (rowIndex >= Rows || columnIndex >= Columns)
8493
throw std::out_of_range("Index out of range");
8594

86-
return m_data[rowIndex * Columns + columnIndex];
95+
if constexpr (StoreType == MatStoreType::ROW_MAJOR)
96+
return m_data[rowIndex * Columns + columnIndex];
97+
98+
else if constexpr (StoreType == MatStoreType::COLUMN_MAJOR)
99+
return m_data[rowIndex + columnIndex * Rows];
100+
101+
else
102+
{
103+
static_assert(false, "Invalid matrix access convention");
104+
std::unreachable();
105+
}
87106
}
88107

89108
[[nodiscard]] constexpr Type &At(const size_t rowIndex, const size_t columnIndex)
@@ -240,6 +259,18 @@ namespace omath
240259
return result;
241260
}
242261

262+
[[nodiscard]]
263+
constexpr const std::array<Type, Rows*Columns>& RawArray() const
264+
{
265+
return m_data;
266+
}
267+
268+
[[nodiscard]]
269+
constexpr std::array<Type, Rows*Columns>& RawArray()
270+
{
271+
return const_cast<std::array<Type, Rows*Columns>>(std::as_const(*this).RawArray());
272+
}
273+
243274
[[nodiscard]]
244275
std::string ToString() const noexcept
245276
{

0 commit comments

Comments
 (0)