What does const do in operator () overloading?

I have a code base in which for the Matrix class these two definitions exist for the operator ():

template <class T> T& Matrix<T>::operator() (unsigned row, unsigned col)
{
    ......
}


template <class T> T Matrix<T>::operator() (unsigned row, unsigned col) const
{
    ......
}

One thing that I understand is that the second does not return the link, but what does it mean constin the second declaration? Also what function is called when I say mat(i,j)?

+3
source share
3 answers

Which function is called depends on whether the instance is const or not. The first version allows you to change the instance:

 Matrix<int> matrix;
 matrix(0, 0) = 10;

Overloading const allows read-only access if you have an instance of a const (reference) Matrix:

 void foo(const Matrix<int>& m)
 {
     int i = m(0, 0);
     //...
     //m(1, 2) = 4; //won't compile
 }

, ( , , ).

T , (er) . T , const const:

 template <class T>
 class MyContainer
 {
      //..,
      T& operator[](size_t);
      const T& operator[](size_t) const;
 }
+6

const const Matrices. .

Matrix<int> M;
int i = M(1,2); // Calls non-const version since M is not const
M(1,2) = 7; // Calls non-const version since M is not const

const Matrix<int> MConst;
int j = MConst(1,2); // Calls const version since MConst is const

MConst(1,2) = 4; // Calls the const version since MConst is const.
                 // Probably shouldn't compile .. but might since return value is 
                 // T not const T.

int get_first( const Matrix<int> & m )
{
   return m(0,0); // Calls the const version as m is const reference
}

int set_first( Matrix<int> & m )
{
  m(0,0) = 1; // Calls the non-const version as m is not const
}
+3

, const. const const :

const Matrix<...> mat;
const Matrix<...>& matRef = mat;
mat( i, j);//const overload is called;
matRef(i, j); //const overloadis called

Matrix<...> mat2;
mat2(i,j);//non-const is called
Matrix<...>& mat2Ref = mat2;
mat2Ref(i,j);//non-const is called
const Matrix<...>& mat2ConstRef = mat2;
mat2ConstRef(i,j);// const is called

. , const. .

+1

Source: https://habr.com/ru/post/1739101/


All Articles