Q1> I have problems to understand the following statement
template<class T> operator T*() const { return 0; }
Specially, what is the meaning of operator T*()
?
It's an implicit conversion operator. It makes it possible to have objects of the type it belongs to implicit convert to the target type T*
here. This version is a special one, since, being a template, it can convert an object of that NullClass
to any pointer type.
Implicit conversion are frowned upon for good reasons. They have the bad habit of kicking in at unexpected moments, making the compiler call an unintended version of an overloaded function. Having a templatized implicit conversion operator is especially evil because templatization multiplies the possibilities.
Q2> Why f(NULL) is finally triggering the f(string*)?
See above. There is no possible conversion to int
, so the implicit conversion operator kicks in and converts an NullClass
object into any pointer requested.
I suppose this is intended. Usually you don't want a pointer to be converted to an integer, which is why that class has an implicit conversion into any pointer, but none to int
.
That NullClass
isn't all that bad, but the NULL
instance of it is pure stupidity. As soon as you include any of the many headers that define the NULL
macro (defined to be 0
, i.e. an integer constant), the preprocessor will trample over all source and replace each usage of NULL
with 0
. Since you can't avoid to include this, this error renders the whole class pretty much useless.