|
Boost : |
Subject: Re: [boost] Proposal: null pointer class
From: Simonson, Lucanus J (lucanus.j.simonson_at_[hidden])
Date: 2009-06-15 16:20:22
Stewart, Robert wrote:
> Simonson, Lucanus J
>>>> template <typename T>
>>>> T null() {return T(); }
>>>>
>>>> int main()
>>>> {
>>>> func(NULL);
>>>> func(null<char*>());
> Note that your function template can be misused because T isn't
> necessarily a pointer type. (That can be added, of course.) With
> that fixed, your function should simply return 0 rather than T().
>
Martin Törnwall wrote:
> You make a good point, but the purpose of the class I proposed is
> very specific -- that of solving problems related to the use of the
> NULL pointer constant. I believe that it could be somewhat confusing
> to have a "null" template function that returns both null pointers
> and objects initialized with the default constructor.
Why? T() is just as portable and there is no need to prevent someone from calling null<string>() or null<char>() because such uses are functionally correct and clear in intent. Lets say we wanted to implement a null terminated sentinel iterator adaptor and make it default to use null<T> if no sentinel value is provided. That would be reasonable to do because you could then specialize null<T> for your type that doesn't provide default constructor instead of having to specify the terminator in the sentinel iterator adaptor every time you use it. Is it confusing that a template named null returns the null value of its parameter and needs to be specialized for types that don't default construct to their null value?
All that said, I'm not sure how much we need this in boost. In my own code I would just use a C-style case in such cases, or reinterpret_cast<char*>(0) if C-style casts were frowned upon by offical style policies. You can't call char*() because it is a syntax error but typedef char* charp; charp() is legal syntax. I template was just doodling with a way to call the pointer default constructor as directly as possible without generating syntax errors. (char*)0 is about the most succinct you can get, but regardless of what you do, you still have an error prone overload because it is up to the user to remember to cast null to the desired pointer type. Since the problem with pointer type overloads and null value is that it is error prone, and not that it is hard to do, I don't think trying to make it easier is solving the real problem. All you can do is avoid defining such overloads in the first place.
Regards,
Luke
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk