Meditation, The Art of Exploitation

Thinking? At last I have discovered it--thought; this alone is inseparable from me. I am, I exist--that is certain. But for how long? For as long as I am thinking. For it could be, that were I totally to cease from thinking, I should totally cease to exist....I am, then, in the strict sense only a thing that thinks.

Friday, December 15, 2006

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);
}