0

I am implementing std::optional, but have run into a snag with one of its copy constructors.

Here is a sketch of my implementation:

#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;
}

The problem is that the compiler complains that optional's constexpr constructor does not have an empty body:

$ 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
     }
     ^

I'm not sure how to initialize optional::m_data otherwise, and I haven't been able to find a reference implementation the web (boost::optional apparently does not use constexpr).

Any suggestions?

Jared Hoberock
  • 11,118
  • 3
  • 40
  • 76
  • 2
    Did you notice in your link that the move and copy ctor are not marked `constexpr`? – Jesse Good Jan 21 '14 at 03:20
  • Digging into the [proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3672.html) they talk about it also: `It is still possible to make the destructor trivial for T's which provide a trivial destructor themselves, and we know an efficient implementation of such optional with compile-time interface — **except for copy constructor and move constructor** — is possible.`. – Jesse Good Jan 21 '14 at 03:41

1 Answers1

2

In C++11 functions and constructors marked as constexpr are very limited in what they can do. In the case of constructors, it cannot contain basically anything other than static_assert, typedef or using declarations or using directives, which rules out calling operator= inside the body of the constructor.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489