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
what is the meaning of
operator T*()
?
It is a user-defined conversion operator. It allows an object of type NullClass
to 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).
Why
f(NULL)
is finally triggering thef(string*)
?
NULL
is of type NullClass
. It can't be converted to an int
, but the user-defined conversion NullClass -> T*
can be used to convert it to a string*
, so void f(string*)
is selected.
Note that this works because there is only one overload of f
that takes a pointer. If you had two overloads,
void f(int*);
void f(float*);
the call would be ambiguous because the NullClass -> T*
conversion can be converted to both int*
and float*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With