Re: 0 vs NULL
On 9/30/2010 1:34 PM, Erik wrote:
It's also possible to write typesafe null-pointer template like.
template<typename T> struct null_ptr
{
static T * value = (T*)(0);
};
In addition to what Daniel said about this code being non-standard, I'd
add that Scott Myers proposed a much nicer solution to this problem in
his Effective C++ 2nd edition item 25. Unfortunately this item was
removed from the 3rd edition, which is the only edition I have an access
to at the moment, so I can't copy it verbatim, but I'll give a general
idea from memory. (BTW, Scott, if you're reading this it would be nice
to know the reason for removing that item. Do you think it's no longer
valid?)
Anyway, the idea was to use a templated conversion operator, something
akin to this:
struct Null_Ptr
{
template <typename T>
operator T * () const
{
return 0;
}
} null_ptr;
//You can use it like this:
int * p = null_ptr; //p is 0
void foo(int *);
void foo(int);
foo(null_ptr);// foo(int *) is called;
And so forth.
But, of course, it also has drawbacks in places where the pointed type
is either overloaded or needs to be deduced, i.e.:
void f(char *);
void f(int *);
f(null_ptr); // - is ambiguous.
template <typename T>
void tf(T * p );
tf(null_ptr); // T can't be deduced
Andy.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]