How might I wrap the FindXFile-style APIs to the STL-style Iterator Pattern in C++?
- by BillyONeal
Hello everyone :)
I'm working on wrapping up the ugly innards of the FindFirstFile/FindNextFile loop (though my question applies to other similar APIs, such as RegEnumKeyEx or RegEnumValue, etc.) inside iterators that work in a manner similar to the Standard Template Library's istream_iterators.
I have two problems here. The first is with the termination condition of most "foreach" style loops. STL style iterators typically use operator!= inside the exit condition of the for, i.e.
std::vector<int> test;
for(std::vector<int>::iterator it = test.begin(); it != test.end(); it++) {
//Do stuff
}
My problem is I'm unsure how to implement operator!= with such a directory enumeration, because I do not know when the enumeration is complete until I've actually finished with it. I have sort of a hack together solution in place now that enumerates the entire directory at once, where each iterator simply tracks a reference counted vector, but this seems like a kludge which can be done a better way.
The second problem I have is that there are multiple pieces of data returned by the FindXFile APIs. For that reason, there's no obvious way to overload operator* as required for iterator semantics. When I overload that item, do I return the file name? The size? The modified date? How might I convey the multiple pieces of data to which such an iterator must refer to later in an ideomatic way? I've tried ripping off the C# style MoveNext design but I'm concerned about not following the standard idioms here.
class SomeIterator {
public:
bool next(); //Advances the iterator and returns true if successful, false if the iterator is at the end.
std::wstring fileName() const;
//other kinds of data....
};
EDIT: And the caller would look like:
SomeIterator x = ??; //Construct somehow
while(x.next()) {
//Do stuff
}
Thanks!
Billy3