Reputation: 15
I'm trying to encapsulate the C++ Standard Library's vector class using templates but I keep getting the error
SceneVector.h: In member function ‘void scenegraph::SceneVector<V>::print()’:
SceneVector.h:40: error: expected ‘;’ before ‘it’
SceneVector.h:40: error: ‘it’ was not declared in this scope
The code I've managed to create is
#include <map>
#include <vector>
#include <iostream>
namespace scenegraph
{
template <class V> class SceneVector
{
typedef std::vector<V> Vector;
Vector vector;
public:
SceneVector();
void insert(const V value);
void print();
};
template <class V> SceneVector<V>::SceneVector()
{
vector.clear();
}
template <class V> void SceneVector<V>::insert(const V value)
{
vector.push_back(value);
}
template <class V> void SceneVector<V>::print()
{
for(Vector::iterator it = vector.begin(); it != vector.end(); ++it)
{
std::cout << "[" << (*it) << "] " << std::endl;
}
std::cout << std::endl;
}
}
Can anyone correct me here? I must reinforce I'm a C++ newbie so the answer may be extremely trivial.
Upvotes: 1
Views: 2457
Reputation: 92271
If you had a plain
std::vector<V>::iterator
it would be pretty obvious that it is dependent name, and that you need a typename
to indicate that iterator is a type.
Using a typedef doesn't really change that.
Upvotes: 3
Reputation: 36049
When accessing types that depend on a template parameter, you must prepend typename
to make clear to the parser that the type is a type.
for(typename Vector::iterator it = vector.begin(); it != vector.end(); ++it)
It is possible for Vector::iterator to be a compile-time constant number, and the compiler can't know that until instantiation time. That's why you have to tell it explicitely.
Upvotes: 3