I am trying to implement a class of numeric vectors. I am using Qt template QVector which is similar to the STL vector
typedef float ArithmeticF;
typedef QVector<ArithmeticF> VectorFloat;
class VectorF : public VectorFloat
{
/// appends the rightSide to the end
VectorF& operator << (const VectorF& rightSide);
}
The thing that confuses me is that
VectorF& VectorF::operator << (const VectorF& rightSide)
{
static_cast<VectorFloat>(*this) << static_cast<VectorFloat>(rightSide);
return *this;
}
does not work at all. I tried to debug it line by line and the VectorFloat::operator<< does not get called at all. There are no errors, the program compiles and runs, but does nothing. However this works:
VectorF& VectorF::operator << (const VectorF& rightSide)
{
VectorFloat a = static_cast<VectorFloat>(*this);
VectorFloat b = static_cast<VectorFloat>(rightSide);
a << b;
*this = VectorF(a);
return *this;
}
I am just curious why is it so. I tried to dig into the static_cast command, but I cannot figure it out.
Please help me.
You are casting to the value type
VectorFloat, which makes a copy of your*thisobject and applies the<<operator to it. This temporary object gets promptly destroyed and thus nothing of effect could be observed.You should cast to the reference
VectorFloat&instead:The fact that second example works is easily explicable. You are storing the copied object in
avariable, and you are reconstructing yourVectorFbased on this modified copy. There are WAY too many operations being done along the way (conversion toVectorFloat, converting back toVectorF, assignment to*this), but in practice it works.