C++11 Accessing Unscoped Enumerators with Qualified Name - c++

I have a question about the wording of the C++11 standard as I have not had to dig into it frequently in the past and recently found myself confused on the (admittedly unimportant) topic of unscoped enums.
I recently came across some code in a code review that was using an unscoped enum but accessing the enumerators using fully qualified names, like this:
enum SomeEnum
{
EnumA,
...
};
void foo()
{
SomeEnum x = SomeEnum::EnumA;
}
I was certain that this didn't work and that SomeEnum had to be an enum class for this behavior, but, sure enough, it compiled cleanly.
Peeking into the C++11 standard, I at first thought that the standard agreed with me:
§ 7.2 Enumeration Declarations: Each enum-name and each unscoped
enumerator is declared in the scope that immediately contains the
enum-specifier. Each scoped enumerator is declared in the scope of the
enumeration.
This appears to me to indicate that unscoped enumerators are declared only at the immediately containing scope of the enum itself. It doesn't mention that they are also declared at the enumeration scope.
However, a little further down, the standard does include an example that shows accessing an unscoped enumerator using the fully qualified name.
A quick bit of googling and searching on SO gave me a small number of places that assert that the standard does now allow the fully qualified name, but there isn't much discussion. Is this just weak wording in the spec that is clarified by the example, or is there something else I'm missing?
Again, this isn't earth shattering, but I'm hoping someone can set me straight on my reading of the standard and I can learn something that may be useful in a future situation.

The quote you are looking for from the draft C++11 standard is from section 5.1 Primary expressions which in paragraph 10 says:
A nested-name-specifier that denotes an enumeration (7.2), followed by
the name of an enumerator of that enumeration, is a qualified-id that
refers to the enumerator. The result is the enumerator. The type of
the result is the type of the enumeration. The result is a prvalue.
It does not restrict the use to scoped enumerations and so the example in section 7.2 Enumeration declarations:
enum direction { left='l', right='r' };
void g() {
direction d; // OK
d = left; // OK
d = direction::right; // OK
}
is entirely consistent. This is also consistent with section 3.4.3 Qualified name lookup which says:
The name of a class or namespace member or enumerator can be referred
to after the :: scope resolution operator (5.1) applied to a
nested-name-specifier that denotes its class, namespace, or
enumeration. [...]
and:
A name prefixed by a nested-name-specifier that nominates an
enumeration type shall represent an enumerator of that enumeration.
again, there is nothing restricting this behavior to scoped enumerations.
Examples are non normative but as long as they don't conflict with the normative text then they should be considered a good guideline.

Related

Return alias identificator instead of type in typeid(SOME_TYPE).name()

In the following example
template <typename T>
void foo() {
const char* name = typeid(T).name();
std::cout << name;
}
the variable 'name' will be initialized by type 'T' name. It is very convinient if we need to print this template type name. But, if we have the alias:
using shortTypeName = std::smth::smth_else::smth_more;
in the result of the call
foo<shortTypeName>();
will be printed 'std::smth::smth_else::smth_more'. And I need to print exactly the alias name, but not the type it is defined. Can somebody give an advice, how I can do this?
... alias identificator ...
There's no such thing, at least not after compilation. It's just syntactic sugar and doesn't exist in any sense in the final executable.
The only way to grab the local name of a type (as opposed to the implementation-defined and probably-mangled typeid name) is with a stringize/stringify macro.
For future reference, this should eventually be possible when the Reflection TS lands - but I don't yet know whether to expect that to look like reflexpr(T).get_name(), or std::meta::name_of(^T), or something else again.
Can somebody give an advice, how I can do this?
The language does not support a mechanism to do this.
What you have is simply a type alias.
From http://en.cppreference.com/w/cpp/language/type_alias:
A type alias declaration introduces a name which can be used as a synonym for the type denoted by type-id. It does not introduce a new type and it cannot change the meaning of an existing type name.
You can't. Because a type alias is transparent: It is just a synonym for a new type, not a new type. As an implementation detail it doesn't even get mangled in the type system because it's not a type.
§7.1.3 The typedef specifier [dcl.typedef]
[...] A name declared with the typedef specifier becomes a typedef-name . Within the scope of its declaration, a typedef-name is
syntactically equivalent to a keyword and names the type associated
with the identifier in the way described in Clause 8. A typedef-name
is thus a synonym for another type. A typedef-name does not
introduce a new type the way a class declaration (9.1) or enum
declaration does.
A typedef-name can also be introduced by an alias-declaration . The identifier following the using keyword becomes a typedef-name and the
optional attribute-specifier-seq following the identifier appertains
to that typedef-name . It has the same semantics as if it were
introduced by the typedef specifier. In particular, it does not
define a new type and it shall not appear in the type-id .
typeid(T).name(); is pretty much useless anyway. Until we have proper introspection in C++ you have to resort to hacks to get what you want (macros, intrusive techniques or external code generator tools).

Inconsistent specialization of tuple_size

When explicitly specializing both tuple_size and tuple_element for some template, I realized that §14.5.1/4, which reads
In a redeclaration, partial specialization, explicit specialization or
explicit instantiation of a class template, the class-key shall agree
in kind with the original class template declaration (7.1.6.3).
is seemingly violated by the standard itself:
Am I missing something here (e.g. the standard specifies that class-keys are "exposition only" and shall agree within the actual implementation)?
Bo Persson's now-deleted answer got it right. The paragraph ([temp.class]/p4) you cite refers to §7.1.6.3 [dcl.type.elab] for the definition of "agree in kind", which in turn says (p3, emphasis mine)
The class-key or enum keyword present in the
elaborated-type-specifier shall agree in kind with the declaration to which the name in the elaborated-type-specifier refers. This rule
also applies to the form of
elaborated-type-specifier that declares a class-name or friend class since it can be construed as referring to the definition of the
class. Thus, in any elaborated-type-specifier, the enum keyword
shall be used to refer to an enumeration (7.2), the union
class-key shall be used to refer to a union (Clause 9), and either the class or struct class-key shall be used to refer to a class
(Clause 9) declared using the class or struct class-key.
The code is valid, if inconsistent.
This looks like an editorial defect to me. Try opening an issue here:
https://github.com/cplusplus/draft/issues
If you're adventurous, try resolving it with a pull request. :-)

Legality of empty, unnamed enumeration specifier

In the example in §7.5 (C++14) one finds:
enum {}; // ill-formed
But, technically speaking, I think the code is valid.enum {} is an enum-specifier, and so, it's a type-specifier, which is a decl-specifier, and thus, it is a simple-declaration with an omitted init-declarator-list. And this is accepted by §7.5. Note that the identifier is optional for an unscoped enumeration. Also, clang compiles this with a warning.
Edit
In relation to the answers mentioning that the *decl-specifier-seq* shall introduce one or more names into the program, or shall redeclare a name introduced by a previous declaration, I show below a typedef declaration that compiles, but whose decl-specifier-seq doesn't introduce any name in the declaration:
typedef class {} A;
In the C++14 FD, right above your example, it is explained why the declaration is ill-formed:
In a simple-declaration, the optional init-declarator-list can be
omitted only when declaring a class (Clause 9) or enumeration (7.2)
[…]
In such cases, the decl-specifier-seq shall introduce one or more
names into the program, or shall redeclare a name introduced by a
previous declaration.
Hence
enum {} e;
enum {a};
Are valid - our quote does not apply to the first declaration as it includes an init-declarator, and the second one introduces the name a as an enumerator. Note that GCC won't compile the first declaration, which is presumably a bug.
You also mentioned the quote
If the enumerator-list is empty, the underlying type is as if the
enumeration had a single enumerator with value 0.
This makes a statement about the underlying type, not the enumeration itself, and is thus irrelevant for this matter.
Why does typedef class {} A; compile?
A is an init-declarator. Yes, it is - [dcl.dcl]/9:
If the decl-specifier-seq contains the typedef specifier, the
declaration is called a typedef declaration and the name of each
init-declarator is declared to be a typedef-name
I.e. the names declared as typedef-names are the init-declarators, by this definition. Hence there is an init-declarator-list, and our above quote isn't applicable.
If you look through the standard, you'll find quite a few things that would be accepted at a purely syntactical level, but are prohibited by the text. This is just one of many instances of that basic idea.
Many of these situations are pretty obvious. Let's consider a really trivial one: a floating point number. Using a syntactical notation similar to that of the standard we could get something like:
"-"opt digits opt "."opt digits opt ("e" "-"opt digits)opt
Everything there is "optional". That doesn't, however, mean that nothingness should be taken as a number. Nor does it mean that (for example) .e is a valid floating point number. It does mean that almost any individual piece can be omitted if some of the others are present. You don't need digits both before and after the decimal point, so each is optional in itself--but one or the other has to be present, so 1. and .1 are both valid, but just . isn't. Likewise, the . is optional as well--something like 1e50 is a perfectly valid floating point literal, even though it doesn't contain a . anywhere.
Those limitations are expressed in the text associated with the syntactic notation itself. What's allowed (or not) has to based on everything taken together, not just on one piece in isolation.
There is clear written in the Standard that (7 Declarations)
...In such cases, and except for the declaration of an unnamed bit-field (9.6), the decl-specifier-seq shall introduce one or more
names into the program, or shall redeclare a name introduced by a
previous declaration.
This declaration
enum {}; // ill-formed
does not satisfy the requirement. It introduces neither name into the program.
As for typedef(s) then
7.1.3 The typedef specifier 1 Declarations containing the decl-specifier typedef declare identifiers that can be used later
for naming 94)

Where can I use alignas() in C++11?

In an effort to standardize my code and make it more portable, I replaced
#ifdef __GNUC__
typedef __attribute__((aligned(16))) float aligned_block[4];
#else
typedef __declspec(align(16)) float aligned_block[4];
#endif
with
typedef float alignas(16) aligned_block[4];
in C++11. However, gnu (4.8) doesn't like that but complains
test.cc:3:9: warning: attribute ignored [-Wattributes]
typedef float alignas(16) aligned_block[4];
^
test.cc:3:9: note: an attribute that appertains to a type-specifier is ignored
whereas clang 3.2 creates no warning (even with -Weverything -Wno-c++98-compat -pedantic).
So I wonder whether my code above is correct and, more generally, where alignas() can and cannot be placed.
EDIT (Apr 2013):
The relevant article from the standard is 7.6.2, in particular 7.6.2.1
An alignment-specifier may be applied to a variable or to a class data member, but it shall not be applied to a bit-field, a function parameter, the formal parameter of a catch clause (15.3), or a variable declared with the register storage class specifier. An alignment-specifier may also be applied to the declaration of a class or enumeration type. An alignment-specifier with an ellipsis is a pack expansion (14.5.3).
as already dug out by Red XIII. However, I'm not expert enough to know what this means for my test above.
If the fact that clang accepts my attribute means anything, it's perhaps worth mentioning that when trying to use a using directive instead of a typedef, clang also complains. Also, contrary to a statement in an earlier version of this question, gcc does not only warn, but indeed ignores my wish for alignment.
I think you just placed the alignas in the wrong position. If you move it directly after the identifier, both GCC and Clang are happy and apply the alignment:
typedef float aligned_block alignas(16) [4];
typedef float aligned_block [4] alignas(16);
this is also true if you use using, where the difference also becomes more apparent. Here are two versions that are not accepted by GCC (warning, alignment ignored):
using aligned_block = float alignas(16)[4];
using aligned_block = float[4] alignas(16);
and here's the accepted one:
using aligned_block alignas(16) = float[4];
I think that GCC applies
7.1.3 The typedef specifier [dcl.typedef]
2 A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. [...]
(emphasis mine)
The above is quite clear for using, the rules for typedef are spread through several paragraphs, including at the end of §8.3/1, where you find:
8.3 Meaning of declarators [dcl.meaning]
1 [...] The optional attribute-specifier-seq following a declarator-id appertains to the entity that is declared.
(again, emphasis mine)
Update: The above answer concentrated on where the alignas has to be placed, not on its exact meaning. After thinking about it some more, I still think that the above should be valid. Consider:
7.6.2 Alignment Specifier [dcl.align]
1An alignment-specifier may be applied to a variable or to a class data member, but it shall not be applied to a bit-field, a function parameter, an exception-declaration (15.3), or a variable declared with the register storage class specifier. An alignment-specifier may also be applied to the declaration or definition of a class (in an elaborated-type-specifier (7.1.6.3) or class-head (Clause 9), respectively) and to the declaration or definition of an enumeration (in an opaque-enum-declaration or enum-head, respectively (7.2)). An alignment-specifier with an ellipsis is a pack expansion (14.5.3).
It lists cases where it can be clearly applied and it lists cases where it clearly can not be applied. The above question's example is neither.
One could also argue that the type alias created by typedef or using is carrying the alignment specification as part of the aliased type. This alias can than be used to create a variable, etc. as allowed by 7.6.2p1 but not to create a variable with register, etc.
In that sense I think that the attribute specifier is applied (in the sense of 7.6.2) in a deferred way and thus OPs example should still be valid when the alignment specification is put in the syntactically correct place.
You cannot apply an alignment to a typedef. In the C++ model of alignment specifiers, the alignment is an inseparable part of the type itself, and a typedef does not create a new type (it only provides a new name for an existing type) so it is not meaningful to apply an alignment specifier in a typedef declaration.
From [dcl.align] (7.6.2)p1:
An alignment-specifier may be applied to a variable or to a class data member [...]. An alignment-specifier may also be applied to the declaration or definition of a class (in an elaborated-type-specifier (7.1.6.3) or class-head (Clause 9), respectively) and to the declaration or definition of an enumeration (in an opaque-enum-declaration
or enum-head, respectively (7.2)).
These are the only places where the standard says an alignment-specifier (alignas(...)) may be applied. Note that this does not include typedef declarations nor alias-declarations.
Per [dcl.attr.grammar] (7.6.1)p4:
If an attribute-specifier-seq that appertains to some entity or statement contains an attribute that is not allowed to apply to that entity or statement, the program is ill-formed.
This wording was intended to apply to alignas as well as the other forms of attribute that may appear within an attribute-specifier-seq, but was not correctly updated when alignment switched from being a "real" attribute to being a different kind of attribute-specifier-seq.
So: your example code using alignas is supposed to be ill-formed. The C++ standard does not currently explicitly say this, but it also does not permit the usage, so instead it currently would result in undefined behavior (because the standard does not define any behavior for it).
Draft C++11 standard http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf says about it (Alignment-specifier is of the form alignas ( assignment-expression )):
7.6.2 Alignment specifier [dcl.align]
1 An alignment-specifier may be applied to a variable or to a class data member, but it shall not be applied
to a bit-field, a function parameter, the formal parameter of a catch clause (15.3), or a variable declared
with the register storage class specifier. An alignment-specifier may also be applied to the declaration of
a class or enumeration type. An alignment-specifier with an ellipsis is a pack expansion.
I found this original proposal http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1877.pdf , it says:
The alignment-specifier does not become part of the type, but it is possible to create a class type
with aligned member variable(s).
with this example:
// Wrong attempt: Listing 6)
typedef double align_by<0x10000> hwDoubleVector; // Error!
Void clear(hwDoubleVector &toClear, unsigned size);
Looks like it's illegal to use it with typedef.
Try:
typedef float alignas(16) aligned_block[4];

Ambiguity Resolution

void S(){}
struct S{};
int main(){
S();
}
In the code above, the expression 'S()' in main is treated as a function call expression rather than an attempt to create a temporary of type 'S'.
Which portion of the C++ Standard talks about the resolution of such an expression in favour of a function declaration? For some reason I am unable to locate it.
Section 3.3.7/2
A class name (9.1) or enumeration name (7.2) can be hidden by the name of an object, function, or enumerator declared in the same scope. If a class or enumeration name and an object, function, or enumerator are
declared in the same scope (in any order) with the same name, the class or enumeration name is hidden
wherever the object, function, or enumerator name is visible.
Then you need to use elaborated type specifier in such cases
3.4.4/1 Elaborated type specifiers
An elaborated-type-specifier may be used to refer to a previously declared class-name or enum-name even
though the name has been hidden by a non-type declaration (3.3.7). The class-name or enum-name in the
elaborated-type-specifier may either be a simple identifer or be a qualified-id.
It can be resolved either by using the scope resolution operator(::) or by using virtual keyword(when we are dealing with either multiple or hybrid inheritance.