Search code examples
c++c++17stdoptional

Using std::optional<A> as a class member of class A


Why isn't it possible to define a class member of type std::optional<A> in class A?

Example:

#include <optional>

class A {
public:
    A(std::optional<A> optional = {}) : optional_(optional) { }
    ~A() = default;
private:
    std::optional<A> optional_;
};

Compiler error:

error: incomplete type 'A' used in type trait expression
   : public integral_constant<bool, __is_trivially_destructible(_Tp)> {};
                                    ^
error: incomplete type 'A' used in type trait expression
   : public integral_constant<bool, __is_constructible(_Tp, _Args...)>
                                    ^

Solution

  • optional<T> requires that T is a complete type (and therefore has a known size). Until the class A's definition is finished, A is an incomplete type. Hence the error.

    There is no way to have any type T hold a member variable of type optional<T>, since optional<T> itself has a member variable of type T. You can heap-allocate an optional<T> (or just a T, since you'd be storing a pointer that could be nullptr).