为什么C++ 11'auto'关键字不适用于静态成员?

sla*_*acy 12 c++ auto c++11

class Foo {
 public:
  static const char *constant_string;
};

auto Foo::constant_string = "foo";

int main(void) {
};
Run Code Online (Sandbox Code Playgroud)

编译:gcc(Ubuntu/Linaro 4.6.3-1ubuntu5)4.6.3像这样:

gcc -std=c++0x ./foo.cc 
./foo.cc:6:11: error: conflicting declaration ‘auto Foo::constant_string’
./foo.cc:3:22: error: ‘Foo::constant_string’ has a previous declaration as ‘const char* Foo::constant_string’
./foo.cc:6:11: error: declaration of ‘const char* Foo::constant_string’ outside of class is not definition [-fpermissive]
Run Code Online (Sandbox Code Playgroud)

这是auto关键字的预期行为,还是gcc +中的错误

Lig*_*ica 11

它被语言所禁止:

[C++11: 7.1.6.4]:

1auto 类型说明符意味着一个变量的类型所声明应从其初始化或一个函数声明来推断应包括一个尾返回型.

2auto 类型说明符可以用具有一个函数声明出现拖尾返回型在这样的声明符是有效的任何上下文(8.3.5).

3否则,变量的类型是从其初始化程序推导出来的.声明的变量的名称不应出现在初始化表达式中.auto在块(6.3),命名空间范围(3.3.6)和for-init-statement(6.5.3)中声明变量时,允许使用此方法.auto应显示为一个DECL-说明符DECL说明符-SEQDECL说明符-SEQ应该跟随一个或多个初始化声明符,其中每一个应具有一个非空的初始值设定.

4 auto 类型说明符还可以用于在声明变量条件的选择语句(6.4)或循环语句(6.5),在类型说明符-SEQ新型-ID类型-ID的一个新的表达式(5.3.4)中,在用于工作范围变换声明,并在声明静态数据成员与支架-或等于初始值设定,该范围内出现构件的规范类定义的(9.4.2) .

5 在本节未明确允许的上下文中使用的程序auto格式不正确.

很难证明是负面的,但auto在你的情况下,标准中根本没有明确的规则允许.

但是,相同的规则意味着以下内容有效:

struct Foo {
   static constexpr auto constant_string = "foo";
};

int main() {}
Run Code Online (Sandbox Code Playgroud)

(注意,类型Foo::constant_string是,char const* const而不是,比如说char const[3]; 这是使用的效果auto.)

  • +1原因是这种情况会很尴尬:`struct foo {static long x; }; auto foo :: x = 0;`初始化程序说类型应该是`int`,但声明说它应该是`long`.应该`auto`强制初始化器(它在其他任何上下文中都没有),如果它无法编译,或者应该'自动'重用现有类型(因此没有用处,只是为了减轻程序员的输入),需要更多的措辞在标准?我确信这就出现了,决定做最简单的事情:完全禁止它. (5认同)

Bru*_*nez 5

Visual C++ 接受

decltype(Foo::constant_string) Foo::constant_string = "foo";
Run Code Online (Sandbox Code Playgroud)