Why does the constexpr attribute not work when applied to a static method?

Consider this trivial test code:

class Test { public: Test() {/* empty */} private: enum {BLAH = 42}; static constexpr int Magic() {return BLAH*4;} float f[Magic()]; }; int main(int argc, char ** argv) { Test t; return 0; } 

When I try to compile it (under MacOS / X, using clang ++ from the latest Xcode), I get this compiler error:

 Jeremys-Mac-Pro:~ jaf$ clang++ -std=c++11 ./test.cpp ./test.cpp:11:14: error: fields must have a constant size: 'variable length array in structure' extension will never be supported float f[Magic()]; 

Can someone explain why this is a mistake? For comparison, if I transfer the Magic () method from the Test class and make it a standalone function, it compiles as expected, but I really do not want to do this because I want to keep Magic () and BLAH if possible, is closed to the class Test

(Note: I am not trying to use variable-length arrays here, rather I am trying to declare an array whose size is determined by the calculation of the function at compile time)

+5
source share
1 answer

This is because functions inside the class are not processed until the class is complete. This rule allows a function defined inside a class to access members of that class that are defined later in the class than this function. As a result, Magic() does not yet have a definition, and therefore cannot be evaluated at that point in time of compilation.

This is the correct behavior, although the error that various compilers generate does not help to understand the problem.

Formal rules are found in the C ++ standard in [class.member] / 6:

A class is considered a fully defined type of object (6.9) (or a full type) when closing } the class specifier. Within a class-class, a class is considered complete in function bodies, default arguments, noexcept specifiers, and default element initializers (including such things in nested classes). Otherwise, it is considered incomplete within its class specification.

+3
source

Source: https://habr.com/ru/post/1273929/


All Articles