开发者

Strong typing of nullptr?

开发者 https://www.devze.com 2023-03-14 16:58 出处:网络
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/

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(ch开发者_运维技巧ar* 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


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*>());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号