Skip to content

not_null comparison functions are missing constexpr #1203

Closed

Description

@LB--

Describe the bug
The comparison operators for not_null such as operator== and operator!= are not declared constexpr, however not_null can be used in constexpr by using .get() instead, so this seems like an oversight.

To Reproduce

#include <gsl/pointers>

constexpr bool example_error(gsl::not_null<int*> const a, gsl::not_null<int*> const b) noexcept
{
    return a == b; //error
}
constexpr bool example_workaround(gsl::not_null<int*> const a, gsl::not_null<int*> const b) noexcept
{
    return a.get() == b.get(); //works
}

Expected behavior
The comparison operators should be constexpr so that the workaround is not necessary.

Spec (please complete the following information):

  • OS: Windows
  • Compiler: both MSVC & ClangCL (VS 2022, 17.13.6)
  • C++ Version: C++17

Additional context
None

Activity

  1. carsonRadtke commented on Apr 30, 2025

    @carsonRadtke
    Member

    Thanks for reporting this issue!

    I suspect this is not an oversight, your workaround requires gsl::not_null<T>::element_type to have a constexpr operator==. Concretely, https://godbolt.org/z/zrqze4sbj will not work with the provided workaround.

  2. LB-- commented on May 1, 2025

    @LB--
    Author

    From my understanding of the C++ standard, a template function can be marked constexpr as long as at least one template instantiation allows it to be used in constexpr evaluation. When it is instantiated in a way that it can't be used in constant evaluation, it just silently ignores the constexpr specifier. This avoids any need to have a conditional constexpr system in the language, letting the compiler make the determination. Therefore, marking those operators as constexpr should not break any existing code.

  3. carsonRadtke commented on May 2, 2025

    @carsonRadtke
    Member

    Ah! You're right, thanks for teaching me :)

    For completeness, it appears the relevant part of the standard is dcl.constexpr#3.2:

    Except for instantiated constexpr functions, non-templated constexpr functions shall be constexpr-suitable.

    I will raise this issue at the next maintainer's sync, and we will discuss how to proceed.

  4. carsonRadtke commented on May 21, 2025

    @carsonRadtke
    Member

    Maintainer's call: Looks like an oversight, update the signature to be constexpr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions