模板中关键字“typename"和“class"的区别?

Difference of keywords #39;typename#39; and #39;class#39; in templates?(模板中关键字“typename和“class的区别?)
本文介绍了模板中关键字“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;
};

推荐答案

typenameclass 在指定模板的基本情况下是可以互换的:

typename and class are interchangeable in the basic case of specifying a template:

template<class T>
class Foo
{
};

template<typename T>
class Foo
{
};

是等价的.

话虽如此,在某些特定情况下,typenameclass 之间存在差异.

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"的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)