jo***********@g mail.com wrote:
typedef typename vector<T>::iter ator iterator_t;
typedef typename vector<T>::cons t_iterator const_iterator_ t;
iterator_t begin() // changed return type to above typedefs
{
return vals.begin();
}
// implement for const objects...
const_iterator_ t begin() const { return vals.begin(); }
Wonderful! I guess my next question is, how did you know to do that? At
this point I don't even know what the 'typedef typename' part of the
above code snippet means. More specifically I suppose is, where can I
get a detailed discussion about templates. Any recommendations on
books? web sites?
Markus answered the question but it may have been a bit confusing.
Without the 'typename' keyword the compiler will think you are trying
to reference a value within the class:
class X
{
public: enum { v };
};
int val = X::v;
is more along the lines of what it thinks you mean because it can't
actually get complete information about the template at this point and
doesn't know what you are talking about. If it looks like a variable
it is unless it isn't....and right now it doesn't know that it isn't.
So you explicitly say, "The next name I use is a type name, not a
variable or value."
Really you are seing this:
typedef type new_name;
where type is "typename temp<type>::int ernal_type".
I did the typedef to abstract the internal representation of the class
so that if vector becomes the wrong container it can be changed without
affecting clients. They will have to be recompiled of course, but you
won't have to do a bunch of editing outside the class to reflect
changes done to its insides. You could even return your own iterator
that might be a simple pointer at some point. It isn't necissary to do
the typedefs, but it is good practice. All clients need to know is
that something that has the interface of an iterator will be returned
from those functions...the y don't need to know exactly what
implementation of an iterator they are getting (although it would be
important to know forward/reverse/random/insert...etc... more may be
necissary to truely encapsulate your type).
You can also read Bruce Eckel's Thinking in C++ V2 online and this
explains what typename is and where it needs to be used.