11

I just read an article on the C++0x standard: http://www.softwarequalityconnection.com/2011/06/the-biggest-changes-in-c11-and-why-you-should-care/

It said nullptr was strongly typed, meaning that it can be distinguished from an integer 0.

f(int);
f(char* p);

f(nullptr); // calls char* version

That's all good, but I'm interesting in knowing what the standard says about nullptr with two pointer functions:

f(char* p);
f(int* p);

f(nullptr);

Do I need a cast here? And is nullptr templated?

f((int*)(nullptr);
f(static_cast<int*>(nullptr));
f(nullptr<int>);               // I would prefer this
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Dov
  • 8,000
  • 8
  • 46
  • 75
  • after you cast `nullptr` to whatever pointer type how is different from casting `NULL`, you got a new target type in both cases. – Gene Bushuyev Jun 21 '11 at 20:47

1 Answers1

10

I haven't read the actual spec on this one, but I'm pretty sure that the call you indicated would be ambiguous without a cast, since a null pointer can be converted to a pointer of any type. So the cast should be necessary.

And no, unfortunately, nullptr is not a template. I really like that idea, though, so you could consider writing a function like this one:

template <typename PtrType> PtrType null() {
     return static_cast<PtrType>(nullptr);
}

And then you could write

f(null<int*>());
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • You should be on the standards committee! That's clean, nice syntax.... Another 50 years and I'm sure it will be in there! – Dov Jun 21 '11 at 19:23
  • 2
    @Dov - I'm not that very impressed over the improvement from the old `f((int*)0);`. Guess that's what the committee considered. – Bo Persson Jun 21 '11 at 20:25
  • @Bo Persson- I think the real advantage here is that, while you still have to cast a null pointer to the proper pointer type, there's no risk that you'll accidentally call a function overloaded on an integral type instead of a pointer type. It also means that you can have a function that's explicitly overloaded on `nullptr_t`, which does actually seem to have some uses. – templatetypedef Jun 21 '11 at 20:32
  • Frankly, null is much more self documenting than 0, but if you have to cast it does lose some of its allure – Dov Jun 21 '11 at 20:36
  • 2
    @templatetypedef - I **am** impressed over `nullptr` and overloading on `nullptr_t`. It is just the utility of `null()` that wasn't overwhelming - sorry. :-) – Bo Persson Jun 21 '11 at 20:43
  • 3
    Personally I would make that `template PtrType* null() { return nullptr; }`, as it makes the usage slightly cleaner. – ildjarn Jun 21 '11 at 23:43