Question: What is the difference between class and TypeName in the following template declarations (template declaration)?
template<class T> class Widget; // uses "class"
template<typename T> class Widget; // uses "typename"
Answer: no different. When declaring a template type parameter (template type parameter), class and typename mean exactly the same thing. Some programmers prefer to use class at all times because it's easier to enter. Other people (including myself) prefer TypeName because it implies that this parameter is not necessarily a class type. A small number of developers use TypeName when any type is allowed, while retaining the class to situations where only user-defined types (user-defined types) are accepted. But from the C + + point of view, class and typename mean exactly the same thing when declaring a template parameter (template parameter).
However, C + + does not always treat class and typename as equals. Sometimes you have to use TypeName. To understand this, we have to discuss the two names you will be involved in a template (template).
Suppose we have a template for a function that can get an object held in a stl-compatible container (STL compatible container) that can be assigned to INTs. Further assume that this function simply prints the value of its second element. It is a silly function that is implemented in a confused way, and as I write below, it can't even compile, but put these aside--there's a way to find out about my stupidity:
template<typename C> // print 2nd element in
void print2nd(const C& container) // container;
{
// this is not valid C++!
if (container.size() >= 2) {
C::const_iterator iter(container.begin()); // get iterator to 1st element
++iter; // move iter to 2nd element
int value = *iter; // copy that element to an int
std::cout << value; // print the int
}
}
I highlighted two local variables (locals) in this function, ITER and value. The type of ITER is c::const_iterator, a type that relies on template parameter (template parameter) C. The name of a template (template) that relies on a template parameter (template parameter) is called dependent names (dependent name). When a dependent names (dependent name) is nested inside a class (class), I call it the nested dependent name (the nested dependent name). C::const_iterator is a nested dependent name (nested dependent). In fact, it is a nested dependent type name (the nested dependent types name), that is, a nested dependent name (the nested dependent name) that involves a type (type).