Skip to content

[Clang] Cannot use a static constexpr/consteval member function to initialize a static constexpr member #126558

@YexuanXiao

Description

@YexuanXiao

I've noticed that static constexpr/consteval member functions exhibit very strange behavior—they can initialize static non-constexpr members but fail to work for static constexpr members.
Example (Godbolt):

struct A
{
    static inline constexpr bool test_constexpr() noexcept
    {
        return true;
    }
    static inline constexpr bool t_expr = test_constexpr(); // can't compile
    static inline constexpr bool test_consteval() noexcept
    {
        return true;
    }
    static inline constexpr bool t_eval = test_consteval();  // can't compile
    static inline bool t_non_const = test_constexpr();
};
inline constexpr bool t_expr = A::test_constexpr();
inline constexpr bool t_eval = A::test_consteval();

Output:

<source>:8:34: error: constexpr variable 't_expr' must be initialized by a constant expression
    8 |     static inline constexpr bool t_expr = test_constexpr();
      |                                  ^        ~~~~~~~~~~~~~~~~
<source>:8:43: note: undefined function 'test_constexpr' cannot be used in a constant expression
    8 |     static inline constexpr bool t_expr = test_constexpr();
      |                                           ^
<source>:3:34: note: declared here
    3 |     static inline constexpr bool test_constexpr() noexcept
      |                                  ^
<source>:15:34: error: constexpr variable 't_eval' must be initialized by a constant expression
   15 |     static inline constexpr bool t_eval = test_consteval();
      |                                  ^        ~~~~~~~~~~~~~~~~
<source>:15:43: note: undefined function 'test_consteval' cannot be used in a constant expression
   15 |     static inline constexpr bool t_eval = test_consteval();
      |                                           ^
<source>:10:34: note: declared here
   10 |     static inline constexpr bool test_consteval() noexcept
      |                                  ^
2 errors generated.
Compiler returned: 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:frontendLanguage frontend issues, e.g. anything involving "Sema"constevalC++20 constevalconstexprAnything related to constant evaluationquestionA question, not bug report. Check out https://llvm.org/docs/GettingInvolved.html instead!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions