The difference between TypeName and class in C + +

Source: Internet
Author: User

In c++template many places have used the TypeName and class these two keywords, and seems to be able to replace, is not these two keywords exactly the same?
Believe that the people who learn C + + are very aware of the keyword class, class is used to define classes, after the introduction of C + + in the template, the first way to define the template is: Template<class t> Here the class keyword indicates that T is a type, and later in order to avoid the use of class in these two places may be confusing, so the introduction of typename this keyword, its role as class indicates that the following symbol is a type, This way, you can use the following method when defining a template: Template<typename t> in the template definition syntax, the keyword class functions exactly like TypeName.
Does TypeName only work in the definition of templates? Not really,TypeName. Another effect is: use nested dependency types (nested depended name)as follows:
#include <iostream>classmyarray{ Public: typedefintLengthtype;}; Template<classT>voidMyMethod (T myarr) {typedef typename T::lengthtype Lengthtype; Lengthtype length=5; printf ("%d", length);}intMain () {MyArray MyArray;    MyMethod (MyArray); return 0;}
This time TypeName's role is to tell the C + + compiler that the string after TypeName is a type name, not a member function or a member variable.
This time if there is no TypeName, the compiler has no way to know whether T::lengthtype is a type or a member name (static data member or static function), so the compilation cannot pass.

The difference between TypeName and class in C + +

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.