class NullClass{
public:
template
operator T*() const {return 0;}
};
I was reading Effective C++ and I came across this
That's the 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 a NullClass
instance, when prompted to convert to any pointer type, will yield the implicit conversion from 0
to said type, i.e. the null pointer for that type.
On a side note, conversion operators can be made explicit :
template
explicit operator T*() const {return 0;}
This avoid implicit conversions (which can be a subtle source of bugs), but permits the usage of static_cast
.