Lets say I am implementing some 2D datastructure (for example a matrix), and I would like to use operator()
for element access. The code could look something like
template <std::size_t M, std::size_t N>
class Matrix {
protected:
std::array<float, M*N> arr;
public:
float operator()(const std::size_t &m, const std::size_t &n) const
{
assert(m < M);
assert(n < N);
return this->arr[m*N + n];
}
float& operator()(const std::size_t &m, const std::size_t &n)
{
// Note that this method body is the exact same as the previous method
assert(m < M);
assert(n < N);
return this->arr[m*N + n];
}
// Waayyy more code such as constructors, etcetera
};
Now I want both of these operator()
methods so that the operator remains useful in cases like const Matrix mat = {1, 0, 1, 0}; std::cout << mat(0,0) << std::endl;
.
But both functions have the exact same body, which seems bad. Is there a way to call one function from the other so that the functionality remains the same, but the code duplication is gone?