What is difference between template <typename T>
and template <class T>
.
For me both are generating the same result.
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
There is no semantic difference between class and typename in a template-parameter. typename however is possible in another context when using templates - to hint at the compiler that you are referring to a dependent type.
An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated. Note the distinction between the terms class template and template class: Class template.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.
There is no difference. typename
and class
are interchangeable in the declaration of a type template parameter.
You do, however, have to use class
(and not typename
) when declaring a template template parameter:
template <template <typename> class T> class C { }; // valid!
template <template <typename> typename T> class C { }; // invalid! o noez!
They're equivalent and interchangeable for most of the times, and some prefer typename because using the keyword class in that context seems confusing.
The reason why typename is needed is for those ambiguous cases when using template <class T>
for example, you define a template like this:
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.
Look at this:
http://www.cplusplus.com/forum/general/8027/
They both produce the same behaviour. When you use typename its more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With