ISO C++ 03对函数范围定义的结构有什么限制?

Bil*_*eal 14 c++ c++03

我们不允许在函数内部定义functor结构,因为不允许在函数模板的实例化中使用函数声明的结构.

还有其他重要的陷阱需要注意吗?例如,这会是坏事:

int foo()
{
    struct Scratch
    {
        int a, b, c;
    };
    std::vector<Scratch> workingBuffer;
    //Blah Blah
}
Run Code Online (Sandbox Code Playgroud)

Alo*_*ave 23

1. C++标准禁止使用本地定义的类和模板.

14.3.1/2:本地类型,没有链接的类型,未命名的类型或从这些类型中复合的类型不应该用作模板类型参数的模板参数.

一个代码示例:

    template <class T> class X { /* ... */ };
    void f()
    {
      struct S { /* ... */ };
      X<S> x3;  // error: local type used as
                //  template-argument
      X<S*> x4; // error: pointer to local type
                //  used as template-argument
    }
Run Code Online (Sandbox Code Playgroud)

以下是IBM文档的更多参考:

2.本地类中的声明只能使用类型名称,枚举,封闭范围内的静态变量,以及外部变量和函数.

代码示例:

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;
}
Run Code Online (Sandbox Code Playgroud)

3.本地类不能拥有静态数据成员

代码示例:

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
    };
}
Run Code Online (Sandbox Code Playgroud)