c++ - uniqueness of struct names -
while name of structure must unique in set of structures within namespace, such name can "shared" variables , functions. example, following code compiles fine:
// code 1 struct h{}; int h{ 8 };
similarly, there no collision in:
// code 2 struct h{}; void h(){}
1) reasoning allow name sharing?
moreover, if throw templates mix, have strange situations. code
// code 3 template< class h > void h(){} struct h{}; template< class h > struct j{}; void j(){}
does compile; following code fails:
// code 4 struct h{}; template< class h > void h(){} void j(){} template< class h > struct j{};
2) why reasoning allowed code 2 not enough allow code 4? not asking rules in standard. asking reason behind rules.
1) reasoning allow name sharing?
according "the design , evolution of c++", bjarne stroustrup, section 2.8.2 "structure tags vs. type names", feature introduced maintain compatibility c. c language requires use of struct
keyword name structure (no keyword required name typedef). can use same identifier declare structure , either function or variable:
struct x { int m; }; void x(void); x(); // call x struct x x; // create new object of type x
a significant syntactic simplification benefit of users introduced c++ @ cost of work implementers , c compatibility problems. [...] in context of c classes [dyp: predecessor of c++], had annoyed me time because made user-defined types second-class citizens syntactically.
[...]
the real need address particular issue came fact standard unix header files, notably,
stat.h
, rely onstruct
, variable or function having same name.-- d&e 2.8.2
2) why reasoning allowed code 2 not enough allow code 4?
i'll first quote c++11 standard:
a class template shall not have same name other template, class, function, variable, enumeration, enumerator, namespace, or type in same scope (3.3), except specified in (14.5.5 [dyp: class template partial specialization]). except function template can overloaded either (non-template) functions same name or other function templates same name (14.8.3 [dyp: refers overloading]), template name declared in namespace scope or in class scope shall unique in scope.
-- c++11 international standard [temp]p5
according interpretation of passage, codes 3 , 4 both illegal. clang++ rejects them, accepts first part of code 3:
template< class h > void h(){} struct h{};
which, according [temp]p5, should illegal well.
considering these examples (3, 4, , beginning of 3) illegal, think rationale don't need compatibility exception in cases: c has no templates.
Comments
Post a Comment