The keyword typename was introduced during the
standardization of C++ to clarify that an identifier inside a template is a
type. Consider the following example:
Here, the second typename is used to clarify that
SubType is a type defined within class T. Thus, ptr
is a pointer to the type T::SubType.
Without typename, SubType would be considered
a static member. Thus, it would be a concrete variable or object. As a result,
the expression
would be a multiplication of the static SubType member
of class T with ptr.
In general, typename has to be used whenever a name
that depends on a template parameter is a type.
A typical application of typename is the access to
iterators of STL containers in template code:
In this function template, the call parameter is an STL
container of type T. To iterate over all elements of the container, the
iterator type of the container is used, which is declared as type
const_iterator inside each STL container class:
Thus, to access type const_iterator of template type
T, you have to qualify it with a leading typename:
The .template Construct
A very similar problem was discovered after the introduction of
typename. Consider the following example using the standard
bitset type:
The strange construct in this example is .template.
Without that extra use of template, the compiler does not know that the
less-than token (<) that follows is not really "less than" but the
beginning of a template argument list. Note that this is a problem only if the
construct before the period depends on a template parameter. In our example, the
parameter bs depends on the template parameter N.
In conclusion, the .template notation (and similar
notations such as ->template) should be used only inside templates
and only if they follow something that depends on a template parameter.
-----------------------------------------------------------------
See Also:
-----------------------------------------------------------------
See Also:
-----------------------------------------------------------------
- Complete Tutorial of C++ Template's
- Standard Template Library Tutorial
- Inter Process Communication Tutorial
- Advance Programming in C & C++
-----------------------------------------------------------------
No comments:
Post a Comment