Typename and class keywords in C ++ Template

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.