"typename"Is a keyword in the C ++ programming language. Another term used in generic programming (template programming"class.[This keyword indicates that the dependent names in the template declaration (or definition) is a type name, not a variable name. In generic programmingtypenameThere are two different interpretations.
1:classThe synonym of a keyword. It is used in the template definition and the template parameter after it is marked as a type parameter.
This is a C ++ generic programming function,typenameKeyword is used to introduce a template parameter, for example:
// Define a general function template <typename T> const T & MAX (const T & X, const T & Y) {If (Y <X) {return X;} return y ;}
In this case,typenameAnother equivalent keyword is available.classAnd have the same functions.
Note: The class here is totally different from the class when defining the class.
2: type name indicator
Is there a problem with the following code?
Template <typename T> void Foo (const T & T) {// declare a pointer to an object of the T: Bar type T: bar * P ;} struct structwithbarastype {typedef int bar;}; int main () {structwithbarastype X; Foo (x );}
This Code seems successful, but compilation fails.
Because the compiler does not knowT::barWhether it is a type name or a variable name. The root cause of this ambiguity is that the compiler does not understandT::barWhether it depends on the template parameter type name or a variable. Note that anybarThe class t of the item can be passed in as a template parameter.foo()Functions, includingtypedefType, enumeration type, or variable.
To eliminate ambiguity, the C ++ language standard stipulates:
A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable Name Lookup finds a type name or the name is qualified the keyword typename.
If there is anotherStructWithBarAsValueType:
struct StructWithBarAsValue { int bar;};
Then the compiler will explain T: bar * P in different ways.
The final solution to the problem is to explicitly tell the compiler,T::barIs a type name. To distinguish it from variables, you must use the typename keyword to tell the Compiler,For example:
Template <typename T> void Foo (const T & T) {// declare a pointer to an object of the T: Bar type, typename T: bar * P ;}
In this way, the compiler determinesT::barIs a type name, P is naturally interpreted as pointingT::barPointer of the type object.