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.
In UML models, template parameters are formal parameters that once bound to actual values, called template arguments, make templates usable model elements. You can use template parameters to create general definitions of particular types of template.
In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.
To instantiate a template class explicitly, follow the template keyword by a declaration (not definition) for the class, with the class identifier followed by the template arguments. template class Array<char>; template class String<19>; When you explicitly instantiate a class, all of its members are also instantiated.
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
.
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