Does C++11 allow declaring non-static data members as 'auto' if they are initialized in the declaration? For example:
struct S
{
auto x = 5; // in place of 'int x = 5;', which is definitely allowed
};
GCC 4.7 rejects the above code, while it accepts int x = 5;
.
Assuming this is not a compiler bug but rather the standard really doesn't allow it, why not? It would be just as useful as declaring local variables auto
.
The rule for prohibiting non-static members is in 7.1.6.4 clause 4:
I found the rationale for it being static here which reflects how James McNellis explains it in the comment.
So, basically depending on the order of header inclusion, the type of
data
could be very different. Of course,auto x = 5;
would not need to depend on 2-phase name lookup or ADL, however, I'm a assuming that they made it a "blanket" rule because otherwise, they would have to make individual rules for every use case which would make things very complicated.In the same paper, the author proposes eliminating this restriction, however, it seems this proposal has been rejected probably due to the above rationale and also so that expected behavior can be the same no matter what the initializer is.
For others:
Using C++17 this is indirectly (automatic deduction of non-static member type) possible. You need to use templates and deduction guides to make it happen:
I don't know how but this auto members really need to make it into the language without them certain patterns are next to impossible.
The scenario above does not work if the lambda captures a member of class by reference. This is a useful pattern for, highly compensable classes that avoid the use of type erased functions. Something I regularly do on embedded systems.
https://godbolt.org/z/W-K9Uk
You can mangle the language into submission allowing a lambda to reference a member of a non-existent class using placement-new and offset_of but that is ludicrous and shouldn't be required.