Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NULL is converted to string*?

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

like image 223
q0987 Avatar asked Dec 02 '22 04:12

q0987


1 Answers

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 the f(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*.

like image 59
James McNellis Avatar answered Dec 03 '22 18:12

James McNellis