Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr(sizeof(T)): Why specify `constexpr` on `sizeof`?

Today someone asked me to help to make a VC++ project compiling with G++ and I stumbled across this line:

static char data[constexpr(sizeof(T))];

(of course it was inside a template function with a template parameter named T).

I don't own a C++ standard but according to cppreference:

Syntax

sizeof( type ) (1)

sizeof expression (2)

Both versions are constant expressions of type std::size_t.

So what is the point on telling VC++ that sizeof() is expected to be constexpr?


Try it: https://rextester.com/VIWP36674.

Works on VC but fails for G++ as expected.

Another option to try: https://godbolt.org/z/DnioLS

Works on VC up to 19.10. Seems to be fixed on 19.14 so I conclude it was really a quirk, but even then, someone must have had a reason to write such code...

like image 401
j4x Avatar asked Nov 07 '22 07:11

j4x


1 Answers

Visual Studio accepts invalid syntax in expressions including constexpr, consteval and constinit keywords. For example, this invalid program is accepted by the latest MSVC:

static_assert( constexpr(sizeof(int)) == sizeof(int) );
static_assert( consteval(sizeof(int)) == sizeof(int) );
static_assert( constinit(sizeof(int)) == sizeof(int) );

Demo: https://gcc.godbolt.org/z/5WqPT74ab

Submitted bug: https://developercommunity.visualstudio.com/t/invalid-expressions-with-constexprconstevalconstin/1626758

like image 180
Fedor Avatar answered Nov 09 '22 23:11

Fedor