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
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
