Difference of keywords #39;typename#39; and #39;class#39; in templates?(模板中关键字“typename和“class的区别?)
问题描述
对于模板,我已经看到了两个声明:
For templates I have seen both declarations:
template < typename T >
template < class T >
有什么区别?
在下面的例子中这些关键字到底是什么意思(取自德语维基百科关于模板的文章)?
And what exactly do those keywords mean in the following example (taken from the German Wikipedia article about templates)?
template < template < typename, typename > class Container, typename Type >
class Example
{
Container< Type, std::allocator < Type > > baz;
};
推荐答案
typename 和 class 在指定模板的基本情况下是可以互换的:
typename and class are interchangeable in the basic case of specifying a template:
template<class T>
class Foo
{
};
和
template<typename T>
class Foo
{
};
是等价的.
话虽如此,在某些特定情况下,typename 和 class 之间存在差异.
Having said that, there are specific cases where there is a difference between typename and class.
第一个是依赖类型的情况.typename 用于在引用依赖于另一个模板参数的嵌套类型时声明,例如本示例中的 typedef:
The first one is in the case of dependent types. typename is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef in this example:
template<typename param_t>
class Foo
{
typedef typename param_t::baz sub_t;
};
您在问题中实际展示的第二个,尽管您可能没有意识到:
The second one you actually show in your question, though you might not realize it:
template < template < typename, typename > class Container, typename Type >
当指定一个模板模板时,class关键字必须像上面一样使用——它不能与typename<互换/code> 在这种情况下(注意:由于 C++17 在这种情况下允许两个关键字).
When specifying a template template, the class keyword MUST be used as above -- it is not interchangeable with typename in this case (note: since C++17 both keywords are allowed in this case).
在显式实例化模板时,您还必须使用 class:
You also must use class when explicitly instantiating a template:
template class Foo<int>;
我确定我遗漏了其他一些情况,但最重要的是:这两个关键字并不等效,而且这些是您需要使用其中一个的一些常见情况.
I'm sure that there are other cases that I've missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.
这篇关于模板中关键字“typename"和“class"的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模板中关键字“typename"和“class"的区别
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
