I’m reading a book on template programming, and one of the examples they have code that does a self check in a templated assignment operator. Basically it’s something like the following:
template <typename T>
class Foo
{
public:
template <typename O>
Foo<T> operator= (const Foo<O> & other)
{
if ((void *)this == (void *)&other)
{
std::cerr << "success" << std::endl;
}
else
{
std::cerr << "failure" << std::endl;
}
return *this
}
};
Now, from my understanding, since the templated assignment operator doesn’t prevent the default assignment operator from being generated, for cases where O = T, the default assignment operator will always be selected over the templated version. That is, in this situation it will never be the case that O = T.
What I’m wondering is whether my understanding of this is correct. If it is, is there some sort of a tricky hierarchy (like if I derive Foo from something else or if it is derived from something else) where the assignment operator will print out “success”?
I’ve tried several things but I can’t really get it to do that.
Thanks in advance
Either you’re right, or both MSVC 11 and g++ 4.7.1 got it wrong.
I.e., normally that templated assignment operator will not be called: the automatically generated copy assignment operator will be called.
To output “success”, do like this, and hope that compiler uses Empty Base class Optimization (EBO):