1

(See for reference What is Allowed in a constexpr Function?)

I know that constexpr functions have some restrictions upon what is allowed in them. The following is a quote lists them.

The function body may contain anything but:

  • an asm declaration
  • a goto statement
  • a statement with a label other than case and default
  • a try-block
  • a definition of a variable of non-literal type
  • a definition of a variable of static or thread storage duration
  • a definition of a variable for which no initialization is performed

I'd like to know, how does the restrictions upon consteval function differ from the one specified above. Is there something that can be allowed in consteval fucntion but not constexpr function, and vise versa.

Karen Baghdasaryan
  • 2,407
  • 6
  • 24
  • The restrictions you mention apply to constant expressions, which are more general than `constexpr` functions. – chris Aug 26 '21 at 10:38
  • 2
    I believe try-blocks are okay in C++20 and beyond. You just may not actually `throw` anything. Makes it easier to write code for either evaluation mode. `throw`'s just translate to compile time errors during compile time evaluation. – StoryTeller - Unslander Monica Aug 26 '21 at 10:49
  • @StoryTeller-UnslanderMonica can you elaborate upon not being allowed to `throw` anything? How does it translate to compile time error? – Karen Baghdasaryan Aug 26 '21 at 10:54
  • 3
    Simple. The compiler stops constant evaluation, points at the throw expression it reached and says "error". So long as it doesn't reach it, no harm. – StoryTeller - Unslander Monica Aug 26 '21 at 10:55

1 Answers1

1

Just like constexpr, consteval makes a function be a constexpr function. The list of requirements (which shrank significantly in C++20 from that C++14 version) applies to that broader category. It’s calls to immediate (i.e., consteval) functions that are further restricted.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • Can you elaborate upon the list of requirements in C++20? – Karen Baghdasaryan Aug 28 '21 at 08:43
  • @KarenBaghdasaryan: It’s down to `goto`/labels and definitions of non-automatic or non-literal variables, and even those should be gone in C++23 (leaving only the parameter/return types, base classes, and invocability). – Davis Herring Aug 28 '21 at 15:49