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 {
public:
// here is the constant !!!
static constexpr int NONE = std::numeric_limits<int>::max();
// ------------------------
Internal(int n = NONE) : _n(n) {}
int get() const { return _n; }
private:
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?