Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a forward declaration within a using statement standard conformant? [duplicate]

In following code, a forward declaration of a class Entity is embedded in a using declaration. The goal is to avoid including "Entity.h" in header files. The code seems to work with different compilers. My question now is whether this code is standard conformant.

using Entities = std::vector<class Entity>;

The following would work, but the above would avoid to duplicate Entity.

class Entity;
using Entities = std::vector<Entity>;

In other words, the question is: Is it necessary to forward declare Entity before std::vector<Entity>, or is std::vector<class Entity> is sufficient?

like image 525
SebastianK Avatar asked Sep 12 '26 17:09

SebastianK


1 Answers

When there is a class named Entity in the outer scope, the class Entity in std::vector<class Entity> refers to that class. On the other hand, class Entity; always declares a class in the current scope. Thus, it's preferable to use a forward declaration.

See [dcl.type.elab]:

If an elaborated-type-specifier is the sole constituent of a declaration, the declaration is ill-formed unless [...], or it has one of the following forms:

class-key attribute-specifier-seqopt identifier ;
class-key attribute-specifier-seqopt simple-template-id ;

In the first case, the elaborated-type-specifier declares the identifier as a class-name. [...]

Otherwise, an elaborated-type-specifier E shall not have an attribute-specifier-seq. If E contains an identifier but no nested-name-specifier and (unqualified) lookup for the identifier finds nothing, E shall not be introduced by the enum keyword and declares the identifier as a class-name. The target scope of E is the nearest enclosing namespace or block scope.

like image 52
cpplearner Avatar answered Sep 15 '26 07:09

cpplearner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!