Differences between typename and class in c ++

Source: Internet
Author: User

I believe that the person who learns C ++ understands the class keyword very well. class is used to define the class. After the c ++ template is introduced, the method for defining the template is: template <class T> ......

Here, the class keyword indicates that T is a type. In order to avoid confusion between the use of class in these two places, the keyword typename is introduced. It works the same way
The same class indicates that the following symbol 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:

Copy codeThe Code is as follows: class MyArray
Typedef int LengthType;

Template <class T>
Void MyMethod (T myarr)
Typedef typename T: LengthType;
LengthType length = myarr. GetLength;

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.

Related Article

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.