Reputation: 16724
I have a class like that (I leave only the relevant part):
template<class T>
class MyList
{
public:
// ....
typename QList<T*>::iterator begin()
{
return list.begin();
}
typename QList<T*>::iterator end()
{
return list.end();
}
typename QList<T*>::iterator skip(int n)
{
auto ite = list.begin();
while(n --> 0)
++ite;
return ite;
}
QList<T*> list;
};
when I went to use the class:
MyList<Foo*> foo;
for(Foo* f : foo.skip(1)) {
I get this error:
'begin' was not declared in this scope
I remove skip()
call, the loop works fine... I don't understand why. Why that and how do I fix this?
Upvotes: 2
Views: 3676
Reputation: 42939
This is just how range-based for loops work in C++. In particular, when in a range expression the participant is a class type, in your case MyList
, for the expression to be legitimate the class type must have defined members begin
and end
.
Member function MyList::skip
returns an iterator to a QList<T*>
. This iterator class doesn't define any begin
and end
members and the compiler renders this type (i.e., the iterator) not a legitimate participant for a range-based for loop expression while the class type MyList
that has defined members begin
and end
renders legitimate.
More info on how a range-for loop works you can find here.
Upvotes: 4