Both typename and class can be used as keywords defined by template parameters ~~
However, the purpose of typename is not limited to this. The following code:
In the above Code, the iter type is C: const_iterator. The actual type depends on the C type. Const_iterator is also the typedef type name in C. However, here, the compiler behavior will not be what you expected.
To illustrate this problem, two concepts are defined: one is the subordinate name and the other is the non-subordinate name. In the above Code, iter isDependent on Template parameter CIs called
The name of the slave. Similarly, value is of the built-in type,Does not depend on any template parametersIs called a non-subordinate name.
When the C ++ compiler faces a subordinate name, if the subordinate name is nested with other types, the iter is of the C: const_iterator type.
C: const_iterator nameIs a nested subordinate type(Nested in the C type, from the template parameter C ). When the compiler sees such code, it will inevitably become dizzy, because it
I don't know whether const_iterator is a class defined in C or a member variable in C. Therefore, consistent compiler Conventions say that for such irresponsible input, the compiler
It is regarded as "this is not a type "!! Obviously, you need to clearly tell it in the code that this is a type, so you only need to add the keyword typename before C: const_iterator.
This is where typename must be used. Tell the compiler to clarify the meaning of the Code. If it is hard to remember, remember the following example:
Template // It can be a class or typename, defining a template
Void f (const C & container, typename C: iterator iter); the first parameter does not require typename, because it does not design nested slave types, it is only a subordinate type (because it is related to C), and the following typename is required.
However, there seems to be some annoying situations here. As mentioned above, before nesting slave types, you need to explicitly tell the compiler that what you need is a type, but some
You cannot do this again.
For example:
1. typename cannot be written before the nested subordinate type appears in the base class list of the class definition.
2. You cannot use typename in the member Initial Value List.
For example:
In short:
In template declaration, class and typename are equivalent.
Typename is used in nested subordinate type definition, except in the initial value column of the member and the base class list.