Search code examples
c++templatesassignment-operator

Assignment operator of template class


I have this example: a class of a matrix and the dimension of the matrix is given as template argument.

template <std::size_t DIM>
class Matrix {
   // ...
};

int main()
{
  Matrix<2> m2;
  Matrix<4> m4;

  m2 = m4;
}

Wat does my assignment operator have to look like to change the the DIM of m2 from 2 to 4?


Solution

  • Wat does my assignment operator have to look like to change the the DIM of m2 from 2 to 4?

    You can't do that, it's impossible.

    You can't change the template argument of an object's class type, it's a static property of the type, not something dynamic that can change at runtime.

    You can change an int from the value 4 to the value 3, but you can't change it to a long. Similarly, you can change a Matrix<2>'s value but you can't change its type to Matrix<4>.

    There is no way to do m2 = m4 and have it mean anything sensible.

    Maybe you want the dimension to be a dynamic property of the type, not a template argument:

    class Matrix {
      std::size_t m_dim;
      // ...
    };
    

    Now you can change the value at runtime, so assigning to the type can change its m_dim value.