c++static-memberslocal-class

Why field inside a local class cannot be static?


void foo (int x)
{
  struct A { static const int d = 0; }; // error
}

Other than the reference from standard, is there any motivation behind this to disallow static field inside an inner class ?

error: field `foo(int)::A::d' in local class cannot be static

Edit: However, static member functions are allowed. I have one use case for such scenario. Suppose I want foo() to be called only for PODs then I can implement it like,

template<typename T>
void foo (T x)
{
  struct A { static const T d = 0; }; // many compilers allow double, float etc.
}

foo() should pass for PODs only (if static is allowed) and not for other data types. This is just one use case which comes to my mind.


Solution

  • Because, static members of a class need to be defined in global a scope, e.g.

    foo.h

    class A {
      static int dude;
    };
    

    foo.cpp

    int A::dude = 314;
    

    Since the scope inside void foo(int x) is local to that function, there is no scope to define its static member[s].