Skip to content

Feature Request: Add C++14 constexpr Support to boost::optional #143

@alandefreitas

Description

@alandefreitas

Currently, boost::optional cannot be used in constexpr contexts in C++14/17 because it lacks constexpr constructors. This limits its usefulness in constexpr-heavy code like compile-time parsers and validators.

constexpr boost::optional<int> g()
{
    return 5;
}

constexpr int y = g().value();
error: constexpr function's return type 'boost::optional<int>' is not a literal type
note: 'optional<int>' is not literal because it is not an aggregate and has 
      no constexpr constructors other than copy or move constructors

https://godbolt.org/z/P667adWE7

Use Case: We're working on adding constexpr support to Boost.URL to enable compile-time URL parsing and validation. Many of the parsing rules naturally return optional values (e.g., optional userinfo, optional port), but we can't use boost::optional in constexpr contexts.

For comparison, boost::system::result already works perfectly in constexpr contexts:

constexpr boost::system::result<int> f()
{
    return 5;
}

constexpr int x = f().value(); // Works fine!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions