Reputation: 13313
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.
Upvotes: 1
Views: 228
Reputation: 22770
You are casting to the value type VectorFloat
, which makes a copy of your *this
object 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:
static_cast<VectorFloat&>(*this) << static_cast<VectorFloat>(rightSide);
The fact that second example works is easily explicable. You are storing the copied object in a
variable, and you are reconstructing your VectorF
based on this modified copy. There are WAY too many operations being done along the way (conversion to VectorFloat
, converting back to VectorF
, assignment to *this
), but in practice it works.
Upvotes: 3