0

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?

Cheiron
  • 3,620
  • 4
  • 32
  • 63
  • call your `float&` operator from your `float` method and return a value. – lakeweb Jun 27 '22 at 16:46
  • 1
    @lakeweb: Can't, as `*this` in the `float` operator will be `const` and hence cannot call the non-const `float&` operator. – DevSolar Jun 27 '22 at 16:47
  • @DevSolar Yes, that's the nub of the whole problem.# – Paul Sanders Jun 27 '22 at 16:48
  • Unrelated to your problem, but in "real" code you shouldn't really use `assert` to validate input. First of all in release-builds it might not even be enabled (i.e. do nothing) and when enabled a failed assertion will crash the program, which isn't very nice for users. A possibly better solution is C++ exceptions, which can then be caught and handled higher up in the code. – Some programmer dude Jun 27 '22 at 16:48
  • And if you pass out references to your data members, you should think about not hiding your data members in the first place. A `struct` or even a plain `typedef` would do. A `vector< vector< float > >`, for example. – DevSolar Jun 27 '22 at 17:00
  • @DevSolar A vector of vectors can be jagged. And needs double pointer dereference to access a single element. And will likely have worse cache performance. – Some programmer dude Jun 27 '22 at 17:02

0 Answers0