### C++ typename and class are not equivalent in template programming

Contrary to the belief most C++ programmers held that class and typename can be used interchangeably or equivalent, there are few occasions that one must use typename instead of class. I think the rule of the thumb is 'use typename instead of class' in template programing, apart from the reason alone that typename by itself is more descriptive of the intention than class.

#include < iostream>

template< typename t =" Val_"> class Cont_{ // class is not allowed.

Val_ sum(Cont_& c) {

Val_ sum = 0;

for (typename Cont_::iterator i = c.begin(); i < c.end(); ++i)

sum += *i;

return sum;

}

template< typename T>

class Test {

T t[3];

public:

typedef T* iterator;

Test() { t[0] = t[1] = t[2] = 1; }

T* begin() {return t;}

T* end() {return t+3;}

};

int main() {

Test< int> test;

std::cout << sum(test);

}

#include < iostream>

template< typename t =" Val_"> class Cont_{ //HERE

Val_ sum(Cont_< val_>& c) {

Val_ sum = 0;

for (typename Cont_< val_>::iterator i = c.begin(); i < c.end(); ++i)

sum += *i;

return sum;

}

template< typename>

class Test {

T t[3];

public:

typedef T* iterator;

Test() { t[0] = t[1] = t[2] = 1; }

T* begin() {return t;}

T* end() {return t+3;}

};

int main() {

Test< int> test;

std::cout << sum(test);

}

#include < iostream>

template< typename t =" Val_"> class Cont_{ // class is not allowed.

Val_ sum(Cont_

Val_ sum = 0;

for (typename Cont_

sum += *i;

return sum;

}

template< typename T>

class Test {

T t[3];

public:

typedef T* iterator;

Test() { t[0] = t[1] = t[2] = 1; }

T* begin() {return t;}

T* end() {return t+3;}

};

int main() {

Test< int> test;

std::cout << sum(test);

}

#include < iostream>

template< typename t =" Val_"> class Cont_{ //HERE

Val_ sum(Cont_< val_>& c) {

Val_ sum = 0;

for (typename Cont_< val_>::iterator i = c.begin(); i < c.end(); ++i)

sum += *i;

return sum;

}

template< typename>

class Test {

T t[3];

public:

typedef T* iterator;

Test() { t[0] = t[1] = t[2] = 1; }

T* begin() {return t;}

T* end() {return t+3;}

};

int main() {

Test< int> test;

std::cout << sum(test);

}

<< Home