I saw the following code:
class NullClass {
public:
template<class T> operator T*() const { return 0; }
};
const NullClass NULL;
void f(int x);
void f(string *p);
f(NULL); // converts NULL to string*, then calls f(string*)
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*()?
Q2> Why f(NULL) is finally triggering the f(string*)?
Thank you
It is a user-defined conversion operator. It allows an object of type
NullClassto be converted to any pointer type.Such conversion operators can often lead to subtle, unexpected, and pernicious problems, so they are best avoided in most cases (they are, of course, occasionally useful).
NULLis of typeNullClass. It can’t be converted to anint, but the user-defined conversionNullClass -> T*can be used to convert it to astring*, sovoid f(string*)is selected.Note that this works because there is only one overload of
fthat takes a pointer. If you had two overloads,the call would be ambiguous because the
NullClass -> T*conversion can be converted to bothint*andfloat*.