The following is reproduced from:
Http://fesir.itpub.net/post/4728/183624
Http://www.cublog.cn/opera/showart.php? Blogid = 18478 & id = 107917
In C ++ template, the typename and class keywords are used in many places, and they seem to be replaceable. Are these two keywords exactly the same? I believe that the C ++ learner understands the class keyword very well. Class is used to define classes. After the C ++ template is introduced, the method for defining the template is as follows:
Template <class T> ......
Here, the class keyword indicates that T is a type. To avoid confusion between the use of class in these two places, the keyword typename is introduced, its function is the same as that of the class, indicating that the symbol behind it is a type, so that you can use the following method when defining the template:
Template <typename T> ......
In the template definition syntax, the keyword class and typename have the same effect.
Does typename only play a role in template definition? In fact, this is not the case. Another role of typename is to use the nested dependency type (nested
Depended name), as shown below:
Class myarray <br/>{< br/> Public: <br/> typedef int lengthtype; <br/> //..... <br/>}< br/> template <class T> <br/> void mymethod (T myarr) <br/>{< br/> typedef typename T :: lengthtype; <br/> lengthtype length = myarr. getlength; <br/>}< br/>
At this time, the role of typename is to tell the C ++ compiler that the string after typename is a type name, not a member function or a member variable. If typename is not mentioned before, the compiler has no way to know whether T: lengthtype is a type or a member name (static data member or static function), so compilation fails.