operator-> is checked for validity;
specifically, at the point of use, not declaration.
operator-> states:
An expressionThis is perfectly valid; however, it doesn't specify when the check of the return-type is to be performed. Most, if not all, compilers check the return-type at the point of the declaration of the overloadedx->mis interpreted as(x.operator->())->mfor a class objectx. It follows thatoperator->()must return either a pointer to a class or an object or or a reference to a class for whichoperator->()is defined.
operator->.
When using templates,
this is too soon and should be deferred until an actual point of use.
operator-> is often overloaded something like this:
template< class T > class pointer {
T *object;
public:
// ...
T& operator* () { return *object; }
T* operator->() { return object; } // line 7
};
However, if we have a pointer<int>, i.e.,
parameterized with a non-class, such as:
main() {
pointer<int> pint;
*pint = 1;
}
then line 7 becomes illegal since operator->
can not return a pointer to an int.
Note that main() does not actually use operator->.
This is an annoyance and greatly complicates the writing of such classes in general and those destined for libraries.
operator->
at the point of declaration goes against the
"only instantiate what you use"
guideline.
So as not to make the treatment of operator->
with templates a special-case,
the checking ought to be done at the point of use
regardless of whether the given class is parameterized or not.
This makes the rule simpler, easier to implement, and easier to teach.
operator-> will still fail;
the only difference is when the check is performed and the error given.