user658266
user658266

Reputation: 2435

What is difference between template <typename T> and template <class T>. For me both are generating the same result

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

Upvotes: 46

Views: 59811

Answers (3)

Ivan Marcin
Ivan Marcin

Reputation: 81

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.

Upvotes: 7

sajoshi
sajoshi

Reputation: 2763

Look at this:

http://www.cplusplus.com/forum/general/8027/

They both produce the same behaviour. When you use typename its more readable.

Upvotes: 2

James McNellis
James McNellis

Reputation: 355079

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!

Upvotes: 70

Related Questions