Re: Returning Nulls in Templates
On Mar 21, 3:39 pm, Ruben Safir <ru...@mrbrklyn.com> wrote:
On Sun, 20 Mar 2011 11:37:37 -0700, James Kanze wrote:
On Mar 20, 3:39 pm, Ruben Safir <ru...@mrbrklyn.com> wrote:
On Sun, 20 Mar 2011 12:03:16 +0000, Paul wrote:
You'd be safer to use '\0' to null-initialise an unkown type.
That can be used for an number type, and pointer as well? That might
be just what I'm looking for.
The correct way to initialize an unknown type is to use T(). That works
for numbers, pointers and smart pointers. Beyond that, as far as the
compiler is concerned, 0, NULL, '\0' and false are all integral
constants evaluating to 0. In code, I've seen two different
conventions: use 0 systematically, for everything (except usually
false), and use 0 for numeric values, NULL for pointers, '\0' for the
nul character, and false for boolean values---in other words, behave as
if the language were logically typed.
But it doesn't work with a string object,
What doesn't work with a string object. A string object doesn't
have a "nul" value, whatever that would mean. Regretfully,
string(0) (or string(NULL)) is a syntactically legal expression,
which results in undefined behavior.
but strangely enough, Victor's
suggestion, which I had though about myself and rejected with out testing
because of the same facts that you stated here, works perfectly for all
the toyes I've tested now. It seems that '\0' is more universal and '0'
No. '\0' and 0 have the same value. The first has type char,
the second type int. Both are null pointer constants (since
both are integral constant expressions evaluating to zero).
However, I would consider code using the first as a null point
defective, since it corresponds to no established convention.
As I said before, if you want a null pointer, use 0 or NULL
(depending on the local conventions). If you want a default
initialized value (e.g. in a template), use T(). If you want a
nullable value (of an arbitrary type), use Nullable<T> (or
Maybe<T>, or Fallible<T>, or boost::optional<T>). And if you
don't know what you want, figure that out first.
--
James Kanze