-
Template troubles II
Greetings, everyone, and don't laugh at me for being a poor novice programmer :)
I'm trying to implement a (very specific) Database class, and I think it'd be nice to be able use some of the generic algorithms on it, like find. So here's my code (stripped to the barest minimum which won't compile):
Code:
#include <vector>
using namespace std;
template<class Type>
class Database {
private:
vector<Type> _data;
public:
vector<Type>::iterator begin() {
return _data.begin();
}
vector<Type>::iterator end() {
return _data.end();
}
};
The compiler says things like 'std::vector<_Ty>::iterator' : dependent name is not a type prefix with 'typename' to indicate a type. Obviously, it has a grudge against me for something.
Or does anyone think otherwise? :)
-
listen to your compiler
Code:
template<class Type>
class Database {
private:
vector<Type> _data;
public:
typename vector<Type>::iterator begin() {
return _data.begin();
}
typename vector<Type>::iterator end() {
return _data.end();
}
};
Why you need typename?
Because without it it thinks iterator is a static member of class vector<Type> and not a type in its own right.
-
you need to add the 'typename' qualifier when referencing a typedef external to a template.
Code:
typename vector<Type>::iterator begin() {
return _data.begin();
}
an easier way is to define the typedef for your template:
Code:
template<class Type>
class Database {
private:
vector<Type> _data;
typedef typename vector<Type>::iterator iterator;
public:
iterator begin() {
return _data.begin();
}
iterator end() {
return _data.end();
}
};