[opensuse-programming] Question on C++ and STL
I have a template class that contains a container:
template <class T>
class MyClass
{
:
private:
std::list<T> ilist;
};
I have no problem accessing the STL container using subscript,
but I am unable to declare an iterator, as an example:
void MyClass<T>::erase(size_t n)
{
std::list<T>::iterator it;
...
g++ gives me an error:
containertest.cc: In member function ‘void MyClass<T>::erase(size_t)’:
containertest.cc:13: error: expected `;' before ‘it’
Note: I've included both <list> and <iterator>.
Now if I declare something like:
std::list<double>::iterator it;
or
std::liststd::string::iterator it;
Everything builds.
One possible solution is to inherit the list, but I wanted to avoid
inheriting STL containers.
--
Jerry Feldman
On Sun, 2007-01-21 at 14:30 -0500, Jerry Feldman wrote:
I have a template class that contains a container: template <class T> class MyClass { : private: std::list<T> ilist; };
I have no problem accessing the STL container using subscript, but I am unable to declare an iterator, as an example: void MyClass<T>::erase(size_t n) { std::list<T>::iterator it; ...
Try replacing this last line with typename std::list<T>::iterator it; The keyword typename has to be used whenever a name that depends on a template parameter is a type. In this case std::list<T>::iterator is a type and so we have to qualify it with typename. I think the rationale here is that you could later define a specialisation of std::list in which iterator was not a type. So the compiler can't be certain that you actually intended for std::list<T>::iterator to be a type until it knows the actual type of T unless you explicitly say that std::list<T> is a type. There are some genuine examples of where this ambiguity can cause problems. You could probably do something like: namespace std { template<> class list<MyOtherClass> { public: enum { iterator }; ... -- JDL --------------------------------------------------------------------- To unsubscribe, e-mail: opensuse-programming+unsubscribe@opensuse.org For additional commands, e-mail: opensuse-programming+help@opensuse.org
participants (2)
-
Jerry Feldman
-
John D Lamb