首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GCC 4.5.3中的nullptr & nullptr_t仿真

GCC 4.5.3中的nullptr & nullptr_t仿真
EN

Stack Overflow用户
提问于 2013-10-22 19:20:44
回答 1查看 988关注 0票数 1

由于一些遗留的原因,我坚持MIPS-GCC 4.5.3。但是,我试图编译的代码在很大程度上使用了C++11 nullptr & nullptr_t,这是GCC 4.5.3中缺少的特性。

在进行了一些googling &进入使用之后,我创建了一个nullptr wrapper,如下所示,但不幸的是,它不能满足一些用例,

代码语言:javascript
复制
namespace std {

class nullptr_t {
public:

nullptr_t() { }
template <typename T> nullptr_t(const T&) { }
template <class T> nullptr_t(const T*) { }
template <class T> nullptr_t(T*) { }
template <typename T, typename  U> nullptr_t(const typename T::U*) { }

template<typename T> operator T*() { return 0;}
template<typename T1, typename T2> operator T1 T2::*() { return 0; }

operator int() const { return 0; }
operator unsigned() const { return 0; }
operator bool() const { return false; }
bool operator == (unsigned i) const { return i == 0; }
bool operator != (unsigned i) const { return i != 0; }
bool operator !() const { return true; }

} nullptr = {};

}

using std::nullptr;

template<typename T> struct DummyContainer {
  DummyContainer(T* ptr)
    : m_ptr(ptr) { }

  DummyContainer(std::nullptr_t)
    : m_ptr(0) { }

  T& operator = (std::nullptr_t)  { return *m_ptr; }

  private: T* m_ptr;
};

int main(int argc, char** argv)
{
  const char* case1 = nullptr; // working
  // I think for below case std::unique_ptr has to be modified to take std::nullptr_t during construction & operator =
  std::unique_ptr<char> case2 =  nullptr; // not working. 
  DummyContainer<char> case3 = nullptr; // working
  case3 = nullptr; //working
  unsigned* case4 = argc > 1 ? nullptr : nullptr; //works


  unsigned* case5 = argc > 2 ? (unsigned*)0 : nullptr; //not working. (It is the major issue as of now)

  return 0;
}

这里的主要案例是unsigned* case5 = argc > 2 ? (unsigned*)0 : nullptr;

IDEONE快照:http://ideone.com/m1mhtB

(多亏了http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2431.pdf)

如有任何建议或建议将不胜感激:)

(注:请避免回答如,升级gcc)

EN

回答 1

Stack Overflow用户

发布于 2013-10-22 19:53:12

下面的解决方案似乎是有效的,

原始资料来源:party/WebKit/Source/wtf/NullPtr.h

代码语言:javascript
复制
namespace std {
class nullptr_t {
public:
    // Required in order to create const nullptr_t objects without an
    // explicit initializer in GCC 4.5, a la:
    //
    // const std::nullptr_t nullptr;
    nullptr_t() { }

    // Make nullptr convertible to any pointer type.
    template<typename T> operator T*() const { return 0; }
    // Make nullptr convertible to any member pointer type.
    template<typename C, typename T> operator T C::*() { return 0; }
private:
    // Do not allow taking the address of nullptr.
    void operator&();
};
}

const std::nullptr_t nullptr;

IDEOne:http://ideone.com/Bnp6th

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19526466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档