码迷,mamicode.com
首页 > 其他好文 > 详细

nullptr 自定义实现

时间:2019-05-22 19:29:31      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:void   public   out   转换操作符   ==   重载   else   允许   nbsp   

nullptr 自定义实现

 

#include <iostream>

#if __cplusplus >= 201703L
#define CPP17
#endif
#if __cplusplus >= 201402L
#define CPP14
#endif
#if __cplusplus >= 201103L
#define CPP11
#endif

#ifdef CPP17
#define CPP17_NAMESPACE std
#else
#define CPP17_NAMESPACE cpp17
#endif
#ifdef CPP14
#define CPP14_NAMESPACE std
#else
#define CPP14_NAMESPACE cpp14
#endif
#ifdef CPP11
#define CPP11_NAMESPACE std
#else
#define CPP11_NAMESPACE cpp11
#endif

namespace cpp11 {}

#ifndef CPP11
namespace cpp11 {

    class nullptr_t {
    public:
        nullptr_t() : _pad(0) {}

        template< class T >
        operator T *() const { // 定义类型转换操作符,使nullptr_t 可转为任意非类成员指针类型。
            return 0;
        }

        template< class C, class T >
        operator T C::*() const { // 重载类型转换操作符,使 nullptr_t 可以转换为类 C 中任意的指针类型(数据成员指针/函数成员指针)。
            return 0;
        }
    private:
        void *_pad; // std requires : sizeof(nullptr_t) == sizeof(void*)
        void operator &() const; // 不允许取地址操作。
    };
    
    const nullptr_t nullptr;
} // namespace cpp11

#endif // #ifndef CPP11

namespace cpp14 {}
namespace cpp17 {}

namespace cpp {
    using namespace ::std;
    using namespace ::CPP11_NAMESPACE;
    using namespace ::CPP14_NAMESPACE;
    using namespace ::CPP17_NAMESPACE;
} // namespace cpp

class A {
public:
      int *a;
};

using namespace cpp;

int main(int argc, char *argv[]) {
    
    int *p = nullptr;
    int A::*a = nullptr;
    cout << "int *p : " << p << endl;
    cout << "int A::*a : " << a << endl;
    cout << "sizeof nullptr : " << sizeof(nullptr) << endl;
    cout << "sizeof void * : " << sizeof(void *) << endl;
    
    return 0;
}

 

支持 c++11 标准的编译器输出:

int *p : 0
int A::*a : 0
sizeof nullptr : 8
sizeof void * : 8

 

仅支持 c++98/c++03 标准的编译输出:

int *p : 0
int A::*a : 0
sizeof nullptr : 8
sizeof void * : 8

 

==================== End

 

nullptr 自定义实现

标签:void   public   out   转换操作符   ==   重载   else   允许   nbsp   

原文地址:https://www.cnblogs.com/lsgxeva/p/10907676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!