Reputation: 397
class NullClass{
public:
template<class T>
operator T*() const {return 0;}
};
I was reading Effective C++ and I came across this class, I implemented the class and it compiles. I have a few doubts over this:
It doesn't have a return type.
What is this operator.
and what it actually does.
Upvotes: 14
Views: 7072
Reputation: 63144
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<class T>
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
.
Upvotes: 15