Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is east constexpr / constinit / consteval allowed in C++20?

Tags:

c++

c++20

Most examples I found on the web preferred the "west style" for constexpr (C++11), consteval, and constinit (C++20):

consteval auto sqr(int n) {
  return n*n;
}
constexpr auto r = sqr(100);  // OK
constinit static auto x = r; 

Since I`m not a language lawyer, I have the following question: Is the "east style" allowed for these specifiers? Example:

auto consteval sqr(int n) {
  return n*n;
}
auto constexpr r = sqr(100);  // OK
static auto constinit x = r; 

To be clear: I do not intent to start a "west" / "east" language war. I'm not interested in opinions, just in facts, especially as clang and gcc head versions on wandbox at this moment give errors but no answers on constinit / consteval.

like image 379
René Richter Avatar asked Sep 20 '19 18:09

René Richter


People also ask

When to use consteval vs constexpr?

In contrast to a constexpr function, a consteval function can only be executed at compile time. consteval creates a so-called immediate function. Each invocation of an immediate function creates a compile-time constant. consteval cannot be applied to destructors or functions that allocate or deallocate.

What is consteval c++?

We use the consteval specifier in C++ to declare an immediate function. An immediate function is a function that must be evaluated at the compile-time to produce a constant. In other words, an immediate function is executed at compile-time.

What is Constinit?

constinit - asserts that a variable has static initialization, i.e. zero initialization and constant initialization, otherwise the program is ill-formed.


1 Answers

Sort of.

It's part of the decl-specifier-seq, and the specifiers in that can be in any order. It's the same rule that allows you to write volatile int static long unsigned inline long const x = 1;

But it isn't part of the declarator (in particular, the ptr-operator), so you can't do int* constexpr x = nullptr;.

like image 157
T.C. Avatar answered Nov 15 '22 09:11

T.C.