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?
template <std::size_t DIM>
class Matrix {
template <std::size_t OtherDim>
Matrix& operator=(const Matrix<OtherDim>& rhs)
{
// whatever magic you need in here
return *this;
}
};
Matrix<DIM>
and Matrix<OtherDim>
are two distinct types.
The first question to ask is, "Is there a logical operation of assigning a Matrix<4>
to a Matrix<2>
?".
The answer is probably "no".
But there probably is a valid assignment between Matrix<2>
and Matrix<2>
:
template <std::size_t DIM>
class Matrix {
// implement a copy constructor...
Matrix(const Matrix& rhs)
: /* copy-initialise all data */
{
/* any other copy-related logic */
}
// ...and a copy-assignment operator
Matrix& operator=(const Matrix& rhs)
{
if (&rhs != this) {
Matrix tmp(rhs);
std::swap(*this, tmp);
}
return *this;
}
};
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.