加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 模板别名范围

发布时间:2020-12-16 09:59:25 所属栏目:百科 来源:网络整理
导读:根据 http://en.cppreference.com/w/cpp/language/type_alias,别名是块级声明.它没有说模板别名有什么特别之处,因此应该读取模板别名也是块级声明. 但是,在块级别上不可能使用模板别名.根据编译器的不同,错误是不同的 – 虽然g给出了一个有意义的消息,说在块
根据 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读