在c ++ 11中实现boost :: optional [英] Implementing boost::optional in c++11

查看:290
本文介绍了在c ++ 11中实现boost :: optional的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用c ++ 11功能实现boost :: optional数据结构。这里是我到目前为止:

I am experimenting with implementing boost::optional like data structure using c++11 features. Here is what I have so far :

template<typename T>
struct maybe {
  bool valid;

  union {
    T value;
  };

  maybe() : valid(false) {}
  maybe(const T& _v) {
  valid = true;
    new (&value) T(_v);
  }
  maybe(const maybe& other) {
    if (other.valid) {
      valid = true;
      new (&value) T(other.value);
    }
    else valid = false;
  }

  ~maybe() {
     if (valid)
       value.~T();
  }

  bool is_valid() { return valid; }

  operator T&() {
    if (valid) return value;
    throw std::bad_exception();
  }
};

我使用无限制联合功能为可选值创建一个正确对齐的空间,存储在原位,而不是动态分配空间。事情主要工作,除非我想创建一个可能<>与参考。例如也许< int&> 导致g ++ 4.7抱怨:

I make use of the unrestricted union feature to create a properly aligned space for the optional value that can be stored in-situ, instead of dynamically allocation space. Things work mostly, except when I want to create a maybe<> with a reference. For instance maybe<int&> causes g++ 4.7 to complain :

error: ‘maybe<int&>::<anonymous union>::value’ may not have reference type ‘int&’
because it is a member of a union

我应该怎么做,可能是类存储引用?

What should I do to make the maybe class store references? Any other improvements/suggestions to the class are also welcome.

推荐答案

要使用引用,这绝对需要明确的专业化,因为你不能放置新的引用:你需要使用指针来存储。

To make this work with references you definitely need an explicit specialization, because you can't do placement new of a reference: you need to use pointers for storage.

除此之外,代码缺少一个副本赋值运算符。移动构造函数和移动赋值运算符也很好(特别是因为这是重新实现 boost :: optional 的第一个原因:boost中的一个缺少它们)。

Beyond that, the code is missing a copy assignment operator. A move constructor, and move assignment operator would also be nice (especially since that's the #1 reason to reimplement boost::optional: the one in boost is lacking them).

这篇关于在c ++ 11中实现boost :: optional的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆