对模板参数使用'class'或'typename'? [英] Use 'class' or 'typename' for template parameters?
问题描述
可能重复:
模板中关键字typename和class的C ++差异
在C ++中定义函数模板或类模板时,可以这样写:
template< class T> ...
或者可以这样写:
template< typename T> ...
有更好的理由吗?
$ b
我接受了最受欢迎的(有趣的)答案,但真正的答案似乎是不,没有好的理由喜欢一个其他。
- 它们是等同的(除了下面的注释)。
- 原因总是使用
typename
。 - 有些人有理由总是使用
class
- 有些人有理由同时使用。
- 有些人不在乎他们使用哪一个。
但是,在模板模板参数的情况下,使用 class
而不是 typename
是必需的。请参阅下面的 user1428839的回答。 (但这种特殊情况不是偏好问题,而是语言的要求。)
Stan Lippman谈到此此处 。我认为这很有趣。
摘要:Stroustrup最初使用 class
在模板中,以避免引入新的关键字。委员会的一些人担心这个关键字的超载会导致混乱。后来,委员会引入了一个新的关键字 typename
来解决句法歧义,并决定让它也用于指定模板类型以减少混淆,但为了向后兼容, class
保持其重载的意义。
Possible Duplicate:
C++ difference of keywords ‘typename’ and ‘class’ in templates
When defining a function template or class template in C++, one can write this:
template <class T> ...
or one can write this:
template <typename T> ...
Is there a good reason to prefer one over the other?
I accepted the most popular (and interesting) answer, but the real answer seems to be "No, there is no good reason to prefer one over the other."
- They are equivalent (except as noted below).
- Some people have reasons to always use
typename
. - Some people have reasons to always use
class
. - Some people have reasons to use both.
- Some people don't care which one they use.
Note, however, in the case of template template parameters, use of class
instead of typename
is required. See user1428839's answer below. (But this particular case is not a matter of preference, it is a requirement of the language.)
Stan Lippman talked about this here. I thought it was interesting.
Summary: Stroustrup originally used class
to specify types in templates to avoid introducing a new keyword. Some in the committee worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword typename
to resolve syntactic ambiguity, and decided to let it also be used to specify template types to reduce confusion, but for backward compatibility, class
kept its overloaded meaning.
这篇关于对模板参数使用'class'或'typename'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!