CPP:定义模板时,通用数据类型 T 是类吗?
CPP:Is generic data type T a class when defining template
定义模板时,格式为:
template <class T> returnType templateName{...};
我的问题是:上述模板声明中的class
关键字会使数据类型 T 成为类吗? 这个问题解释如下:
在<class T>
中,T 应该是数据类型的名称,并且前面有"class"。在 cpp 中学习类时,我知道定义了一个类:class ClassName{...};
。所以我的理解是,类关键字后面的所有内容都是类的名称。在模板声明的情况下,在T
之前还有一个class
关键字。这是否意味着 CPP 中的数据类型也是类?
在
<class T>
中,T
应该是数据类型的名称,并且前面是"class"。这是否意味着 CPP 中的数据类型也是类?
答案是否定的。
定义模板时,无论是类模板还是函数模板,都可以使用typename
以及class
。typename
是更准确的描述,但也支持class
,很可能是出于历史原因。
因此
template <typename T> struct Foo {};
与
template <class T> struct Foo {};
可以使用任何类型作为模板参数来创建对象。它可以是基本类型之一,也可以是用户定义的类型之一(又名class
es/struct
s(。
给出上面的类模板,可以使用:
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
相关文章:
- 如何使虚函数接受仅在派生类中定义的数据类型?
- 错误 - 自定义数据类型作为有效负载,带有提升::几何
- 如何使用宏根据参数定义不同的数据类型?
- C++哈希表 - 如何解决自定义数据类型作为键的unordered_map冲突?
- 运算符重载以显示用户定义的数据类型
- CPP:定义模板时,通用数据类型 T 是类吗?
- 从自定义数据类型向量中删除重复元素
- C++:自定义数据类型向量错误的队列
- 即使基类和派生类只使用基元数据类型,我是否需要定义虚拟析构函数
- 是否可以用类似C/C++(或任何语言)的语言,从作为用户输入的字符串或文件中创建用户定义的数据类型
- 交换未定义数据类型中的字节顺序
- 在 C++ 中设置的用户定义数据类型
- C++ - 按自定义数据类型向量的值删除元素
- 具有数据类型的C 抽象基础将在派生类中定义
- QML自定义列表数据类型
- 如何为数据类型 vector<glm::vec3> (opengl 数据类型) 编写 std::minmax 函数的自定义比较器
- 如何初始化用户定义的数据类型的STD ::可选
- 如何在不在类对象中重新定义类类型的情况下将数据类型定义为结构中的int
- 我们可以只为某些数据类型定义一个模板函数吗?
- openv数据类型定义