Template alias scope

孤者浪人 提交于 2019-12-02 00:12:27

问题


As per http://en.cppreference.com/w/cpp/language/type_alias, aliases are block-level declarations. It doesn't say anything special about template aliases, so it should be read that template aliases are block-level declarations as well.

However, it is impossible to use template aliases at block level. The errors are different depending on the compiler - while g++ gives a meaningful message, saying that templates are not allowed at block scope, clang is completely cryptic. (example: http://coliru.stacked-crooked.com/a/0f0862dad6f3da61).

Questions I have so far:

  • Does cppreference fail to specify that template aliases can not be used at block scope? (Or do I need to take a reading course?)
  • Are the compilers correct in denying template aliases on block level (the feature I find very interesting for my particular coding habits)
  • If the answer to the second is Yes, what might be the rationale for this? Why would compiler deny me this pure syntax sugar?

回答1:


An alias template is [temp.alias]

A template-declaration in which the declaration is an alias-declaration (Clause 7) declares the identifier to be a alias template. An alias template is a name for a family of types. The name of the alias template is a template-name.

And if we look at 14.2 [temp] we have

A template-declaration can appear only as a namespace scope or class scope declaration. In a function template declaration, the last component of the declarator-id shall not be a template-id.

So yes cppreference is off saying that it can be declared at block scope and your compilers are correct. If you do click on the link of block declarations It will bring you to a list of declarations and in that it has Template declaration and in there it has

declaration of a class (including struct and union), a member class or member enumeration type, a function or member function, a static data member at namespace scope, a variable or static data member at class scope, (since C++14) or an alias template (since C++11) It may also define a template specialization.

As for why the standard says that templates can only be declared in namespace scope or class scope I like James Kanze answer

The problem is probably linked to the historical way templates were implemented: early implementation techniques (and some still used today) require all symbols in a template to have external linkage. (Instantiation is done by generating the equivalent code in a separate file.) And names defined inside a function never have linkage, and cannot be referred to outside of the scope in which they were defined.




回答2:


The compilers are behaving correctly.

Section 14 of the C++14 standard:

A template-declaration can appear only as a namespace scope or class scope declaration.



来源:https://stackoverflow.com/questions/32768034/template-alias-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!