Re: typename keyword
On 10 Apr., 23:18, cplusle...@gmail.com wrote:
I have a basic question about the keyword 'typename'. typename has to
be used whenever a name that depends on a template parameter is a
type. But in the function foo() below I am using
vector<int>::const_iterator without typename. How does this work? How
does the compiler know that const_iterator is not a static member?
////////////////////////////////////////////////////////////////
using std::vector;
template <typename T>
void foo(T const& cont, vector<int> vec)
{
typename T::const_iterator tIter = cont.begin(); //This is OK
vector<int>::const_iterator vecIter = vec.begin(); //How does this
work without typename
You need to use the typename prefix, if a qualified name depends on
a template parameter. In the case "vector<int>::const_iterator"
this dependency is now "resolved" (it is said, that "vector<int>" is
non-dependent), the compiler "knows" the actual type of vector<int>.
Therefore it can found out, whether "vector<int>::const_iterator"
specifies a type or something else.
"typename" used in this context is required for still depending
templates, e.g. consider that you had used "vector<T>::const_iterator"
inside your function template foo above. Because it is possible
- per language - to write a specialization of std::vector for which
"vector<T>::const_iterator" does either *not* exist at all or is not
a type, the programmer must help the compiler here.
typename vector<int>::const_iterator vecTypIter = vec.begin(); //do I
really need typename in this case.
You don't need typename here, because vector<int> is no
dependent type. It is allowed to write that in C++03 in
a template context, and it will probably be lifted to be
allowed outside of a template context in C++0x (for reasons
of simplicity for the programmer).
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]