Keyword typename
In the process of C ++ standardization, the keyword typename is introduced for illustration; the identifier inside the template can be a type. For example:
template<typename T>class MyClass{ typename T::SubType *ptr; ...};
In the above program, the 2nd typename is used to describe that subtype is a type defined within Class T. Therefore, PTR is a pointer to the T: subtype type.
If you do not use typename, subtype will be considered as a static member, so it should be a specific variable or object. Therefore, the following expression:
T: subtype * PTR;
It is regarded as the product of the static member subtype and PTR of the class T.
. Template Construction
After we introduced typename, we found a very similar problem. Consider the following example using the standard bitset type:
template<int N>void printBitset(std::bitset<N> const& bs){ std::cout<<bs.template to_string<char,char_traits<char>,allocator<char> >();}
In this example, there is a strange structure:. template. If this template is not used, the compiler will not be aware of the following facts: BS. the smaller sign (<) after the template is not the smaller sign in mathematics, but the starting symbol of the template real parameter list. Therefore, only before the editor judges that the smaller sign (<) is dependent on the template parameter construction, this problem occurs. In this example, the incoming parameter BS is constructed based on the template parameter n.
Use this->
For base class templatesThe name X is not necessarily the same as this-> X. This is true even if X is inherited from the base class. For example:
Template <typename T> class base {public: void exit () ;}; template <typename T> class derived: Base <t> {public: void Foo () {exit (); // call an external exit () or an error occurs }};
In this example, when Foo () decides which exit () to call, the exit () defined in the base class is not considered (). Therefore, if you do not get an error, you call another exit ().
Note: For symbols declared in the base class that depend on template parameters (functions or variables), you should use this-> or base <t> before them: :. If you want to completely avoid uncertainty, you can (use such as this-> and base <t>:) limit (in the template) all the members to access.
Skills in template Programming