c++ – How can there be no begin()/end() for directory_iterator to work for range based loop?


for(const auto& entry : std::filesystem::directory_iterator("some-directory"))

This is a typical use of filesystem::directory_iterator to traverse a folder. I can imitate it to implement a foo_iterator with following code:

class foo_iterator {
    public:
        class iterator {
        public:
            iterator(int _value) : value(_value) {}
            
            iterator& operator++() { ++value; return *this; }
            
            iterator operator++(int) { iterator temp = *this; ++value; return temp; }
            
            int operator*() const { return value; }
            
            bool operator!=(const iterator& other) const { return value != other.value; }
        private:
            int value;
        };
        foo_iterator(int _count) : count(_count) {}
        
        iterator begin() const {
            return iterator(0); // 从0开始 
        }
        
        iterator end() const {
            return iterator(count); 
        }
    private:
        int count;
    };

    int main() {
        for (auto i : foo_iterator(10)) {
            std::cout << i << ' '; // 输出 0 1 2 3 4 5 6 7 8 9 
        } std::cout << std::endl; return 0;
    }

I have to write begin() and end() for it. But there is no such member functions for directory_iterator, there are only 2 global functions (at least in the VS2022 sdk):

_NODISCARD inline directory_iterator begin(directory_iterator _Iter) noexcept {
    return _Iter;
}

_NODISCARD inline directory_iterator end(directory_iterator) noexcept {
    return {};
}

What’s the trick behind it?

Edit:
I tried to write the 2 functions for my foo_iterator, but it didn’t work, why?

    class foo_iterator {
    public:
        foo_iterator(){}
        foo_iterator(int count) : count(count) {}
        //foo_iterator& operator++() { ++count; return *this; }
        bool operator++() { ++value; return value >= count; }
        bool operator!=(const foo_iterator& o) { return value != o.value; }
    private:
        int value = 0;
        int count = 0;
    };

    foo_iterator begin(foo_iterator it) { return it; }
    foo_iterator end(foo_iterator) { return {}; }

    int main() {
        for (auto i : foo_iterator(10)) {
            std::cout << i << ' '; // 输出 0 1 2 3 4 5 6 7 8 9 
        } std::cout << std::endl; return 0;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *