可能的重复:
模板中关键字'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模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)