c – 模板别名范围

c – 模板别名范围,第1张

概述根据 http://en.cppreference.com/w/cpp/language/type_alias,别名是块级声明.它没有说模板别名有什么特别之处,因此应该读取模板别名也是块级声明. 但是,在块级别上不可能使用模板别名.根据编译器的不同,错误是不同的 – 虽然g给出了一个有意义的消息,说在块范围内不允许模板,clang是完全神秘的. (例如:http://coliru.stacked- 根据 http://en.cppreference.com/w/cpp/language/type_alias,别名是块级声明.它没有说模板别名有什么特别之处,因此应该读取模板别名也是块级声明.

但是,在块级别上不可能使用模板别名.根据编译器的不同,错误是不同的 – 虽然g给出了一个有意义的消息,说在块范围内不允许模板,clang是完全神秘的. (例如:http://coliru.stacked-crooked.com/a/0f0862dad6f3da61).

到目前为止我遇到的问题:

> cppreference是否无法指定模板别名不能在块范围内使用? (或者我需要参加阅读课程吗?)
>编译器是否在块级别上拒绝模板别名是正确的(我觉得这个特性对于我的特定编码习惯非常有趣)
>如果第二个答案是肯定的,那么这可能是什么原因?为什么编译器会否认我这种纯语法糖?

解决方法 别名模板是[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.

如果我们看一下14.2 [temp]我们有

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.

所以是的,cppreference说它可以在块范围内声明并且你的编译器是正确的.如果你点击block declarations的链接它将带你到一个声明列表,并且它有Template declaration并且在那里它有

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.

至于为什么标准说模板只能在命名空间范围或类范围内声明,我喜欢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.

总结

以上是内存溢出为你收集整理的c – 模板别名范围全部内容,希望文章能够帮你解决c – 模板别名范围所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1216915.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存