What is the T * operator (where T is the template parameter) in C ++?

class NullClass{ public: template<class T> operator T*() const {return 0;} }; 

I read Effective C ++ and I came across this class, I implemented the class and compiles it. I have a few doubts about this:

  • It has no return type.

  • What kind of operator is this?

  • and what he really does.

+7
c ++ operator-overloading
source share
1 answer

This is a type conversion operator. It defines an implicit conversion between an instance of the class and the specified type (here T* ). Its implicit return type is, of course, the same.

Here, the NullClass instance, when requested to convert to any type of pointer, will lead to an implicit conversion from 0 to the specified type, i.e. null pointer for this type.

On the side of the note, conversion operators can be made explicit:

 template<class T> explicit operator T*() const {return 0;} 

This avoids implicit conversions (which can be a subtle source of errors), but allows the use of static_cast .

+10
source share

All Articles