How to declare a compile-time constant scope to a class within a local scope

I have a class defined within a function. An object of that class type is instantiated later in the function, and I want to define a constant inside that class, which is referred to from the function.

Live code

void foo() {
    class Internal {
        // here is the constant !!!
        static constexpr int NONE = std::numeric_limits<int>::max();
        // ------------------------
        Internal(int n = NONE) : _n(n) {}
        int get() const { return _n; }
        int _n;
    Internal x(123), y;
    if (x.get() == Internal::NONE) {
       std::cout << "x" << std::endl; // not printed
    if (y.get() == Internal::NONE) {
       std::cout << "y" << std::endl; // printed

This yields a compile error:

error: local class ‘class foo()::Internal’ shall not have static data member ‘constexpr const int foo()::Internal::NONE’ [-fpermissive]

Removing the static, leaving just constexpr, results in:

error: non-static data member ‘NONE’ declared ‘constexpr’

Just using const results in:

error: invalid use of non-static data member ‘foo()::Internal::NONE’

FWIW, static const doesn’t work either.

Is there any way to accomplish this aside from moving the constant out of the class scope?


No, static constexpr members are banned from local classes. Probably because it wasn’t free for compilers to implement it, unlike local classes. (Where is its storage declared? When is it initialized? Etc. All could be answered, but getting those answers right is a cost).

 static constexpr int NONE(){ return std::numeric_limits<int>::max(); }

this, however, works.

Leave a Reply

Your email address will not be published. Required fields are marked *