Why is the C ++ 11 keyword 'auto' not working for static members?

class Foo { public: static const char *constant_string; }; auto Foo::constant_string = "foo"; int main(void) { }; 

Compiled with: gcc (Ubuntu / Linaro 4.6.3-1ubuntu5) 4.6.3 as follows:

 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] 

Is this the intended behavior of the auto keyword or a bug in gcc +

+11
c ++ c ++ 11 auto
Jan 11 '13 at 19:22
source share
2 answers

It is not allowed by language:

[C++11: 7.1.6.4]:

1 The type auto means that the type of the declared variable must be inferred from its initializer or that the function declarator must include the return type of the return value.

2 An auto type auto can appear using a function declarator with a return type of return type (8.3.5) in any context in which such a declarator is valid.

3 Otherwise, the type of the variable is inferred from its initializer. The name of the declared variable should not appear in the initializer expression. This use of auto allowed when declaring variables in block (6.3), in the namespace area (3.3.6), and in for-init-statement (6.5.3). auto should appear as one of the decl specifiers in the -seq specifier, and one or more init-declarators should follow in the -seq specifier, each of which must have a non-empty initializer.

4 A specifier of type auto can also be used when declaring a variable in the condition of a select statement (6.4) or an iteration operator (6.5), in a specifier type-seq in the identifier of a new type or in the identifier type of a new expression (5.3.4), in the declaration for range and when declaring a static data element with, which appears in the specification of the class definition element (9.4.2).

5 A program that uses auto in a context not explicitly permitted in this section is poorly formed.

It is difficult to prove a negative result, but there is no explicit rule in the standard allowing auto in your case.

However, the same rules mean that the following is true:

 struct Foo { static constexpr auto constant_string = "foo"; }; int main() {} 

(Note that the type Foo::constant_string is char const* const , not, say, char const[3] ; this is the effect of using auto .)

+10
Jan 11 '13 at 19:28
source share

Visual C ++ accepts

 decltype(Foo::constant_string) Foo::constant_string = "foo"; 
+2
Jul 31 '15 at 2:52
source share



All Articles