CPP:定义模板时,通用数据类型 T 是类吗?

CPP:Is generic data type T a class when defining template

本文关键字:数据类型 定义 CPP      更新时间:2023-10-16

定义模板时,格式为:

template <class T> returnType templateName{...};

我的问题是:上述模板声明中的class关键字会使数据类型 T 成为类吗? 这个问题解释如下:

<class T>中,T 应该是数据类型的名称,并且前面有"class"。在 cpp 中学习类时,我知道定义了一个类:class ClassName{...};。所以我的理解是,类关键字后面的所有内容都是类的名称。在模板声明的情况下,在T之前还有一个class关键字。这是否意味着 CPP 中的数据类型也是类?

<class T>中,T应该是数据类型的名称,并且前面是"class"。这是否意味着 CPP 中的数据类型也是类?

答案是否定的。

定义模板时,无论是类模板还是函数模板,都可以使用typename以及classtypename是更准确的描述,但也支持class,很可能是出于历史原因。

因此

template <typename T> struct Foo {};

template <class T> struct Foo {};

可以使用任何类型作为模板参数来创建对象。它可以是基本类型之一,也可以是用户定义的类型之一(又名classes/structs(。

给出上面的类模板,可以使用:

struct Bar {}; // User defined type
Foo<Bar> f1;   // Using user defined type to create the object f1
Foo<int> f2;   // Using a fundamental type to create the object f2