What restrictions does ISO C++03 place on structs defined at function scope?

后端 未结 5 1994
情深已故
情深已故 2020-12-10 13:06

We\'re not allowed to define a functor struct inside a function because one is not allowed to use function declared structs in the instantiation of function templates.

5条回答
  •  死守一世寂寞
    2020-12-10 13:34

    1. C++ standard forbids using locally-defined classes with templates.

    14.3.1/2: A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

    A code example:

        template  class X { /* ... */ };
        void f()
        {
          struct S { /* ... */ };
          X x3;  // error: local type used as
                    //  template-argument
          X x4; // error: pointer to local type
                    //  used as template-argument
        }
    

    Here is a little more reference from IBM documentation:

    2. Declarations in a local class can only use type names, enumerations, static variables from the enclosing scope, as well as external variables and functions.

    A Code Example:

    int x;                         // global variable
    void f()                       // function definition
    {
          static int y;            // static variable y can be used by
                                   // local class
          int x;                   // auto variable x cannot be used by
                                   // local class
          extern int g();          // extern function g can be used by
                                   // local class
    
          class local              // local class
          {
                int g() { return x; }      // error, local variable x
                                           // cannot be used by g
                int h() { return y; }      // valid,static variable y
                int k() { return ::x; }    // valid, global x
                int l() { return g(); }    // valid, extern function g
          };
    }
    
    int main()
    {
          local* z;                // error: the class local is not visible
          return 0;
    }
    

    3. A local class cannot have static data members

    A Code Example:

    void f()
    {
        class local
        {
           int f();              // error, local class has noninline
                                 // member function
           int g() {return 0;}   // valid, inline member function
           static int a;         // error, static is not allowed for
                                 // local class
           int b;                // valid, nonstatic variable
        };
    }
    

提交回复
热议问题