微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 为什么在这个类定义中不需要空参数列表?

当仅使用标准类型参数实例化具有模板化类类型的变量时,语法如下所示:
template<typename Arg = int>
class Templ;

Templ<>& myTempl;

省略空参数列表<>应该给出编译错误,因为需要模板参数列表.

但显然(至少在VS2013下),以下声明不需要模板参数列表:

template<typename Arg> //" = int" left out
class Templ{
    Templ& myTempl; //no <> here
};

但为什么这有效呢?根据IntelliSense,编译器选择了正确的类型(Templ< int>),因此它按预期工作,但成员声明是否仍然需要空参数列表?

编辑:不,它没有按预期工作.我没有仔细检查.当将鼠标悬停在Templ< short> :: myTempl行上时,IntelliSense会将其类型显示为较短.

解决方法

名称被注入类范围

9个班级[班级]

2 A class-name is inserted into the scope in which it is declared
immediately after the class-name is seen. The class-name is also
inserted into the scope of the class itself; this is kNown as the
injected-class-name
. For purposes of access checking,the
injected-class-name is treated as if it were a public member name. A
class-specifier is commonly referred to as a class deFinition. A class
is considered defined after the closing brace of its class-specifier
has been seen even though its member functions are in general not yet
defined. The optional attribute-specifier-seq appertains to the class;
the attributes in the attribute-specifier-seq are thereafter
considered attributes of the class whenever it is named.

类似于类模板

14.6.1本地声明的名称[temp.local]

1 Like normal (non-template) classes,class templates have an
injected-class-name
(Clause 9). The injectedclass- name can be used as
a template-name or a type-name. When it is used with a
template-argument-list,as a template-argument for a template
template-parameter,or as the final identifier in the
elaborated-typespecifier of a friend class template declaration,it
refers to the class template itself. Otherwise,it is equivalent to
the template-name followed by the template-parameters of the class
template enclosed in <>.

这样您就可以使用Templ,意思是Templ< Arg>.

原文地址:https://www.jb51.cc/c/117045.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐