I want to make sure that *this != &rhs in the assignment operator. But it won’t compile. Any suggestions?
template <typename T>
class A {
public:
A() {
std::cout << "Default Constructor" << std::endl;
}
A(const T& t) : m_t(t) {
std::cout << "Templated Constructor" << std::endl;
}
template <typename X>
A( const A<X>& rhs ) : m_t( (static_cast< A<T> >(rhs)).m_t ) {
std::cout << "Copy Constructor" << std::endl;
}
template <typename X>
const A& operator=( A<X>& rhs) {
std::cout << "Assignment Operator" << std::endl;
if (this != static_cast< A<T>* > (&rhs) )
m_t = rhs.get();
return *this;
}
T get() { return m_t; }
private:
T m_t;
};
class base {};
class derived : public base {};
int main()
{
A<base*> test1;
A<derived*> test2;
test1 = test2;
}
I personally think the following is the most elegant solution. I am not sure why I didn’t get that in the first place – I initially was using the bloodshed c++ compiler and it seemed to fail – but g++ this is cleanest?
If people disagree with me, I’ll remove my answer and give it to someone else. Note that the A* actually means A* but is note required