对于模板,我已经看到了两个声明:
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"的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!