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
{
Public:
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.