I wrot e a template which successfully works for ints, floats, doubles etc. It includes a method which does a swap between two members of the class.
For example:
the class decl.
Code:
template< class T1, class T2 >
class Pair {
public:
Pair();
Pair(const T1 &x, const T2 &y) : first(x), second(y) {}
~Pair();
void setPairX(const T1 &x);
void setPairY(const T2 &y);
T1 getPairX() const { return first; } //inline def
T2 getPairY() const { return second; } // inline def
void swap();
private:
T1 first;
T2 second;
};
the void swap definition looks like this:\
Code:
template< class T1, class T2 >
void Pair< T1, T2 >::swap()
{
union { T1 tmpX; T2 tmpY; };
if (typeid(first) == typeid(T1)) {
tmpX = first;
first = static_cast<T1>(second);
second = static_cast<T2>(tmpX);
}
else {
tmpY = first;
first = static_cast<T2>(second);
second = static_cast<T1>(tmpY);
}
}
My question is: why this doesn't work for "strings"? I get compiler errors, complaining about the anonymous union I used in swap method. Why is that? These two do not work together?
I'm kinda new to C++, trying hard to memorize all the rules...