`static constexpr` function called in a constant expression is…an error?

As T.C. demonstrated with some links in a comment, the standard is not quite clear on this; a similar problem arises with trailing return types using decltype(memberfunction()). The central problem is that class members are generally not considered to be declared until after the class in which they’re declared is complete. Thus, regardless of the … Read more

enum vs constexpr for actual static constants inside classes

For the record, the static constexpr version will work like you’d expected in C++17. From N4618 Annex D.1 [depr.static_constexpr]: D.1 Redeclaration of static constexpr data members [depr.static_constexpr] For compatibility with prior C++ International Standards, a constexpr static data member may be redundantly redeclared outside the class with no initializer. This usage is deprecated. [Example: struct … Read more

Why is this constexpr static member function not seen as constexpr when called?

From memory, member function bodies are evaluated only once the class has been completely defined. static constexpr int bah = static_n_items(); forms part of the class definition, but it’s referring to a (static) member function, which cannot yet be defined. Solution: defer constant expressions to a base class and derive from it. e.g.: struct Item_id_base … Read more

Compile-time or runtime detection within a constexpr function

It is possible to detect if a given function-call expression is a constant expression, and thereby select between two different implementations. Requires C++14 for the generic lambda used below. (This answer grew out this answer from @Yakk to a question I asked last year). I’m not sure how far I’m pushing the Standard. This is … Read more

Throw in constexpr function

clang is correct, note the HEAD revision of gcc accepts also accepts this code. This is a well-formed constexpr function, as long as there is value for the argument(s) that allows the function to be evaluated as a core constant expression. In your case 1 is such a value. This is covered in the draft … Read more

Understanding the example on lvalue-to-rvalue conversion

This is because y.n is not odr-used and therefore does not require an access to y.n the rules for odr-use are covered in 3.2 and says: A variable x whose name appears as a potentially-evaluated expression ex is odr-used unless applying the lvalue-to-rvalue conversion (4.1) to x yields a constant expression (5.19) that does not … Read more