模板中关键字“typename”和“class”的C ++差异 [英] C++ difference of keywords 'typename' and 'class' in templates
问题描述
对于模板,我已经看到两个声明:
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 >
指定模板模板时,
关键字必须如上所述使用 - 在此情况下不可与 typename
互换。
When specifying a template template, the class
keyword MUST be used as above -- it is not interchangeable with typename
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”的C ++差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!