sdm@cs.brown.edu (Scott Meyers) (05/30/91)
I've been doing some thinking lately about how to implement NULL such that
NULL is distinguishable from the integer 0, i.e., given functions
f(int x);
f(T *x); // T is any type; what's important is that x is a pointer
a call to f(0) will call the former (as currently happens) and f(NULL) will
call the latter. This precludes the old #define approach. The motivation
for this, by the way, is that when you have overloaded functions such as
the above, it's clumsy and error-prone to invoke f with the null pointer,
since you have to say f((T*) 0) in order to be sure to get the right
function.
As I see it, the problem boils down to the fact that NULL must be of
pointer type, but type compatible with all pointers without a cast.
So here's my latest thought, but since I don't have a compiler supporting
templates, I don't know if it will work:
class NullClass {
public:
template <class T> operator T*() const { return 0; }
};
extern NullClass NULL;
The idea here is that given a call to f(NULL), the compiler will try to
convert the object NULL into either an int or a pointer-to-T, and since
there's no defined conversion to an int, it'll invoke the appropriate
conversion operator to a pointer. The attractive thing about it is that
the compiler instantiates template functions upon implicit demand, so the
NULL object should be silently convertable into a pointer of any type.
Anybody know if this will work or not? Are template member functions
allowed inside non-template classes?
Scott
-------------------------------------------------------------------------------
What do you say to a convicted felon in Providence? "Hello, Mr. Mayor."
chip@tct.com (Chip Salzenberg) (06/01/91)
According to sdm@cs.brown.edu (Scott Meyers): > class NullClass { > public: > template <class T> operator T*() const { return 0; } > }; > > extern NullClass NULL; This approach loses when NULL is used for a non-class pointer. For example, this code fragment won't work with NullClass: extern time_t time(time_t *t); main() { time_t t = time(NULL); } -- Chip Salzenberg at Teltronics/TCT <chip@tct.com>, <uunet!pdn!tct!chip> perl -e 'sub do { print "extinct!\n"; } do do()'
dsouza@gwen.cad.mcc.com (Desmond Dsouza) (06/08/91)
In article <77091@brunix.UUCP> sdm@cs.brown.edu (Scott Meyers) writes: > So here's my latest thought, but since I don't have a compiler supporting > templates, I don't know if it will work: > class NullClass { > public: > template <class T> operator T*() const { return 0; } > }; > extern NullClass NULL; > Scott Nice idea, but: ARM, p 342: A template declaration can only appear as a global declaration -- Desmond. -- ------------------------------------------------------------------------------- Desmond D'Souza, MCC CAD Program | ARPA: dsouza@mcc.com | Phone: [512] 338-3324 Box 200195, Austin, TX 78720 | UUCP: {uunet,harvard,gatech,pyramid}!cs.utexas.edu!milano!cadillac!dsouza