C++ 模板 <typename T> 和模板 <class T> 之间有什么区别。对我来说,两者都产生相同的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5307036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is difference between template <typename T> and template <class T>. For me both are generating the same result
提问by user658266
What is difference between template <typename T>
and template <class T>
.
For me both are generating the same result.
有什么区别template <typename T>
和template <class T>
。对我来说,两者都产生相同的结果。
for example
例如
template <class T>
T Average(T *atArray, int nNumValues)
{
T tSum = 0;
for (int nCount=0; nCount < nNumValues; nCount++)
tSum += atArray[nCount];
tSum /= nNumValues;
return tSum;
}
if I change it to template <typename T>
it's the same
如果我把它改成 template <typename T>
是一样的
回答by James McNellis
There is no difference. typename
and class
are interchangeable in the declaration of a type template parameter.
没有区别。 typename
并且class
在类型模板参数的声明中可以互换。
You do, however, have to use class
(and not typename
) when declaring a template template parameter:
但是,在声明模板模板参数时,您必须使用class
(而不是typename
):
template <template <typename> class T> class C { }; // valid!
template <template <typename> typename T> class C { }; // invalid! o noez!
回答by Ivan Marcin
They're equivalent and interchangeable for most of the times, and some prefer typename because using the keyword class in that context seems confusing.
在大多数情况下,它们是等效和可互换的,有些人更喜欢 typename,因为在该上下文中使用关键字 class 似乎令人困惑。
The reason why typename is needed is for those ambiguous cases when using template <class T>
for example, you define a template like this:
需要 typename 的原因是在使用时那些不明确的情况template <class T>
,例如,您定义这样的模板:
template <class T>
void MyMethod() {
T::iterator * var;
}
and then for some reason the user of your template decides to instantiate the class as this
然后出于某种原因,您的模板的用户决定将类实例化为
class TestObject {
static int iterator; //ambiguous
};
MyMethod<TestObject>(); //error
It becomes ambiguous what var should be, an instance of a class iterator or the static type int. So for this cases typename was introduced to force the template object to be interpreted as a type.
var 应该是什么、类迭代器的实例或静态类型 int 变得不明确。因此,对于这种情况,引入了 typename 以强制将模板对象解释为类型。
回答by sajoshi
Look at this:
看这个:
http://www.cplusplus.com/forum/general/8027/
http://www.cplusplus.com/forum/general/8027/
They both produce the same behaviour. When you use typename its more readable.
它们都产生相同的行为。当您使用 typename 时,它的可读性更高。