I'm implementing range-based FOR loops for a custom class, but I need to retain compatibility with older compilers. To that end, my implementation goes like this
class FooArrayIterator
{
public:
FooArrayIterator(const FooArray& container, unsigned int index = 0)
:_container(container),
_index(index)
{}
bool operator != (const FooArrayIterator& other)
{
return (_index != other._index);
}
int operator*() const;
const FooArrayIterator& operator++()
{
_index++;
return *this;
}
private:
const FooArray _container;
unsigned int _index;
};
int FooArrayIterator::operator*() const
{
return _container[_index];
}
FooArrayIterator begin(FooArray& container)
{
return FooArrayIterator(container, 0);
}
FooArrayIterator end(FooArray& container)
{
return FooArrayIterator(container, container.length());
}
However, when testing:
FooArray c;
c.append(0);
...
c.append(9);
for (auto n : c)
{
std::cerr << "Number is: " << n << endl;
fflush(stderr);
}
It fails to compile, saying "this range-based 'for' statement requires a suitable "begin" function and none was found". I was under the impression that I could get away with a free-standing begin() and end() functions. Is this not possible?
Aucun commentaire:
Enregistrer un commentaire