Skip to content

Instantly share code, notes, and snippets.

@Mikle-Bond
Created May 5, 2016 09:19
Show Gist options
  • Save Mikle-Bond/1c5c7f8b60cf028314a276267f6285a4 to your computer and use it in GitHub Desktop.
Save Mikle-Bond/1c5c7f8b60cf028314a276267f6285a4 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cstdlib>
#include <algorithm>
// dd.hpp
template <typename Derived>
struct DD_traits;
template <typename T>
class DD
{
private:
using T_ret_type = typename DD_traits<T>::ret_type;
protected:
typename DD_traits<T>::ret_type **body_;
size_t size_x, size_y;
explicit DD(size_t x, size_t y) {
// if we got exception here, so there were no changes
body_ = new T_ret_type * [x];
// if all is ok, it should be filled with nullptrs. just in case.
std::fill_n(body_, x, nullptr);
try {
for (size_t i = 0; i < x; ++i)
body_[i] = new T_ret_type [y] ();
} catch (...) {
for (size_t i = 0; i < x; ++i)
// it is safe to delete it, due to nulls.
delete [] body_[i];
throw;
}
size_x = x, size_y = y;
}
~DD() {
for (int i = 0; i < size_x; ++i)
delete [] body_[i];
delete [] body_;
}
public:
class RowLine {
T_ret_type *row_;
public:
RowLine (T_ret_type *row) : row_(row) {}
T_ret_type & operator[] (size_t j) {
return row_[j];
}
};
friend class ::DD<T>::RowLine;
RowLine operator[] (size_t i) {
return RowLine(body_[i]);
}
};
// matrix.h
class Matrix;
template <>
struct DD_traits<Matrix>
{
using ret_type = int;
};
class Matrix : public DD<Matrix>
{
public:
explicit Matrix (size_t x, size_t y) : DD<Matrix>(x, y) {}
};
// main.cpp
int main ()
{
Matrix m(5, 5);
m[1][3] = 5;
std::cout << m[1][3];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment