0

我正在实施std::optional,但遇到了其中一个复制构造函数的障碍。

这是我的实现的草图:

#include <type_traits>

template<typename T>
class optional
{
  public:
    constexpr optional()
      : m_is_engaged(false)
    {}

    constexpr optional(const optional &other)
      : m_is_engaged(false)
    {
      operator=(other);
    }

    constexpr optional &operator=(const optional &other)
    {
      if(other.m_is_engaged)
      {
        return operator=(*other);
      }
      else if(m_is_engaged)
      {
        // destroy the contained object
        (**this).~T();
        m_is_engaged = false;
      }

      return *this;
    }

    template<typename U>
    optional &operator=(U &&value)
    {
      if(m_is_engaged)
      {
        operator*() = value;
      }
      else
      {
        new(operator->()) T(value);
        m_is_engaged = true;
      }

      return *this;
    }

    T* operator->()
    {
      return reinterpret_cast<T*>(&m_data);
    }

    T &operator*()
    {
      return *operator->();
    }

  private:
    bool m_is_engaged;
    typename std::aligned_storage<sizeof(T),alignof(T)>::type m_data;
};

#include <tuple>

int main()
{
  optional<std::tuple<float, float, float>> opt;

  opt = std::make_tuple(1.f, 2.f, 3.f);

  return 0;
}

optional问题是编译器抱怨constexpr构造函数没有空体:

$ g++ -std=c++11 test.cpp 
test.cpp: In copy constructor ‘constexpr optional<T>::optional(const optional<T>&)’:
test.cpp:15:5: error: constexpr constructor does not have empty body
     }
     ^

我不确定如何初始化optional::m_data,而且我无法在网络上找到参考实现(boost::optional显然不使用constexpr)。

有什么建议么?

4

1 回答 1

2

在 C++11 中,标记为constexpr的函数和构造函数的功能非常有限。在构造函数的情况下,它基本上不能包含除static_assert,typedefusing 声明using 指令之外的任何内容,这排除operator=了在构造函数体内调用的可能性。

于 2014-01-21T03:38:00.547 回答