可能的重复:
模板中关键字'typename'和'class'的C++差异
在 C++ 中定义函数模板或类模板时,可以这样写:
When defining a function template or class template in C++, one can write this:
template <class T> ...
或者可以这样写:
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."
typename
.class
.但是请注意,在 C++17 之前,对于 template 模板 参数,需要使用 class
而不是 typename
.请参阅下面的user1428839 的回答.(但这种特殊情况不是偏好问题,而是语言的要求.)
Note, however, that before C++17 in the case of template template parameters, use of class
instead of typename
was required. See user1428839's answer below. (But this particular case is not a matter of preference, it was a requirement of the language.)
Stan Lippman 谈到了这个 此处.我觉得这很有趣.
Stan Lippman talked about this here. I thought it was interesting.
总结:Stroustrup 最初使用 class
在模板中指定类型以避免引入新关键字.委员会中的一些人担心关键字的这种超载会导致混淆.后来,委员会引入了一个新的关键字typename
来解决句法歧义,并决定让它也用于指定模板类型以减少混淆,但为了向后兼容,class
保留其重载的含义.
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"作为模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!