gpt4 book ai didi

c++ - 模板特化是扩展还是覆盖通用模板?

转载 作者:可可西里 更新时间:2023-11-01 16:26:01 24 4
gpt4 key购买 nike

template<typename T>
struct A{
void method1(){}
};

template<>
struct A<int>{
void method2(){}
};

威尔A<int>有method1和method2吗?和 A<float>只会有 method1

最佳答案

每个特化都会带来一种全新的数据类型(或全新的模板,如果特化只是部分的)。来自标准 (C++11):

(§14.5.5/2) Each class template partial specialization is a distinct template and definitions shall be provided for the members of a template partial specialization (14.5.5.3).

和:

(§14.5.5.3/1) [...] The members of the class template partial specialization are unrelated to the members of the primary template. Class template partial specialization members that are used in a way that requires a definition shall be defined; the definitions of members of the primary template are never used as definitions for members of a class template partial specialization. [...]

以上内容是在部分特化的上下文中陈述的,但它也适用于显式特化(如您的情况),尽管标准并未明确说明这一点。

另请注意,您不仅需要在特化中声明所需的所有成员函数,还需要定义它们(此处,标准甚至对显式特化也非常明确):

(14.7.3/5) A member of an explicitly specialized class is not implicitly instantiated from the member declaration of the class template; instead, the member of the class template specialization shall itself be explicitly defined if its definition is required. In this case, the definition of the class template explicit specialization shall be in scope at the point at which the member is defined. The definition of an explicitly specialized class is unrelated to the definition of a generated specialization. That is, its members need not have the same names, types, etc. as the members of a generated specialization. [...]

所以,确实,A<int>只会有 method2() , 和 A<float>只会有 method1()作为成员(member)。此外,如果您要介绍 method1()A<int>同样特化,它不需要与 A<float>::method1() 具有相同的参数类型或返回类型.

请参阅@aschepler 的回答,了解避免为 int 重写模板定义的可能方法。案例。

关于c++ - 模板特化是扩展还是覆盖通用模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16765179/

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