Search code examples
c++booststdconstexprboost-optional

Can I return an optional from a constexpr function?


  • Can I return an optional from a constexpr function?
  • Why?
  • If yes, how does it work?

I'm interested in both boost::optional and std::optional. Do they behave the same?


Solution

  • boost::optional cannot be returned by a constexpr function. Or at least, the documentation provides no guarantees of this.

    However, std::optional, as defined by the accepted C++14 proposal, can be returned by a constexpr function. But only if the type argument of the optional is trivially destructible.

    This allows the destructor of std::optional to be trivial in those cases. At which point, there's no difficulty in destroying the object, so there's nothing stopping std::optional from being a literal type.

    The proposal is quite clear on this. If T is trivially destructible, then most of the constructors of optional will be constexpr, and optional<T> will be a literal type. And therefore, it can be created in a constexpr function.