c++templatesgeneric-programmingtemplate-classesclass-template

Class Template non-type member access in sub-class


I have a Matrix class template which looks like this:

using matrix_size_t = unsigned int;
using matrix_data_t = double;

template <matrix_size_t row, matrix_size_t col>
class Matrix
{
protected:
    matrix_data_t m_matrix[row][col];

//more code irrelevant to the question...
}

I also have a subclass template SquareMatrix that looks like this:

template <matrix_size_t size>
class SquareMatrix :public Matrix<size, size>
{
public:
    matrix_data_t trace()
    {
        matrix_data_t trace{ 0 };
        for (matrix_size_t j{ 0 }; j < size; ++j)
        {
            trace += m_matrix[j][j]; //C3861 error in MVS: m_matrix identifier not found
        }
        return trace;
    }
};

The problem is: I'm not able to access the member m_matrix from the subclass.

When I substitute m_matrix with Matrix<size,size>::m_matrix, the sub-class code works:

template <matrix_size_t size>
class SquareMatrix :public Matrix<size, size>
{
public:
    matrix_data_t trace()
    {
        matrix_data_t trace{ 0 };
        for (matrix_size_t j{ 0 }; j < size; ++j)
        {
            trace += Matrix<size, size>::m_matrix[j][j]; //this works
        }
        return trace;
    }
};

I don't know if this is the right thing to do. Please help me understand what is going on!


Solution

  • I don't know if this is the right thing to do.

    Yes. You can also use this->m_matrix instead.

    m_matrix is a nondependent name, which won't be looked up in the dependent base class Matrix<size, size>, it depends on the template parameter size. Making m_matrix dependent as Matrix<size, size>::m_matrix or this->m_matrix, then the name would be looked up at the time of instantiation, at that time the base class specialization that must be explored will be known.