C++11,关于nullptr

謠言 2011-11-23 12:22:31
很简单的一个类就能实现C++11中nullptr的全部功能,为什么新标准还要定义一个关键字呢?
标准的演进原则不是说“能用库完成的就不修改语言来实现”的吗?

struct nullptr_t
{
template<class T> operator T() const;
template<class T> operator T*() const { return 0; }
template<class T> bool equal(T) const;
template<class T> bool equal(T* p) const { return 0 == p; }
};

template<class P>inline bool operator==(nullptr_t n, P p){ return n.equal(p); }
template<class P>inline bool operator==(P p, nullptr_t n){ return n.equal(p); }
template<class P>inline bool operator!=(nullptr_t n, P p){ return !n.equal(p); }
template<class P>inline bool operator!=(P p, nullptr_t n){ return !n.equal(p); }

namespace { nullptr_t nullptr; }
...全文
183 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
謠言 2011-11-23
  • 打赏
  • 举报
回复
更正nullptr_t定义:
struct nullptr_t
{
template<class T> operator T*() const { return 0; }
template<class T> bool equal(T* p) const { return 0 == p; }
};
对象 2011-11-23
  • 打赏
  • 举报
回复
给LZ摘一段0x的文档:


Re nullptr: It must be copyable, throwable, and passable through varargs.
• Re the type of nullptr: It should be named, and be a POD type. Named variables
of this type are allowed. reinterpret_cast to and from this type is allowed. It is
both a pointer type and a pointer-to-member type; i.e., it matches both a T* and a
T::* partial specialization. If it matches two partial specializations, you have an
ambiguity.
• Re the name of the type of nullptr: nullptr_t is introduced as a typedef for
decltype(nullptr).
In addition, this paper includes proposed wording for the feature.


原文:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2214.pdf

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧