gpt4 book ai didi

c++ - 为什么此类定义中不需要空参数列表?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:32 27 4
gpt4 key购买 nike

当仅使用标准类型参数实例化具有模板类类型的变量时,语法如下所示:

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 显示其类型为 short .

最佳答案

类名被注入(inject)类作用域

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> .

关于c++ - 为什么此类定义中不需要空参数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25038479/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com