强类型的nullptr?

Dov*_*Dov 11 types nullptr c++11

我刚读了一篇关于C++ 0x标准的文章:http://www.softwarequalityconnection.com/2011/06/the-biggest-changes-in-c11-and-why-you-should-care/

它表示nullptr强类型,这意味着它可以与整数0区分开来.

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

f(nullptr); // calls char* version
Run Code Online (Sandbox Code Playgroud)

这一切都很好,但我很有兴趣知道标准说nullptr两个指针功能:

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

f(nullptr);
Run Code Online (Sandbox Code Playgroud)

我需要演员吗?是nullptr模板化的吗?

f((int*)(nullptr);
f(static_cast<int*>(nullptr));
f(nullptr<int>);               // I would prefer this
Run Code Online (Sandbox Code Playgroud)

tem*_*def 10

我还没有看过这个的实际规格,但是我很确定你指出的调用在没有强制转换的情况下是不明确的,因为空指针可以转换为任何类型的指针.所以演员阵容应该是必要的.

不幸的nullptr是,不是模板.不过我真的很喜欢这个想法,所以你可以考虑写一个像这样的函数:

template <typename PtrType> PtrType null() {
     return static_cast<PtrType>(nullptr);
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以写了

f(null<int*>());
Run Code Online (Sandbox Code Playgroud)

  • 我个人会做`template <typename PtrType> PtrType*null(){return nullptr; },因为它使用量稍微清洁. (3认同)
  • @Dov - 我对旧的`f((int*)0);`的改进印象不深.猜猜这是委员会考虑的内容. (2认同)
  • @templatetypedef - 我**在'nullptr`上留下深刻印象并在`nullptr_t`上重载.它只是`null <int*>()`的实用程序,不是压倒性的 - 抱歉.:-) (2认同)