Use #39;class#39; or #39;typename#39; for template parameters?(使用“class或“typename作为模板参数?)
问题描述
可能的重复:
模板中关键字'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"作为模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用“class"或“typename"作为模板参数?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
