Last active
May 21, 2019 21:17
-
-
Save nsmaciej/892ce282607031ce41f0e36e236e3cb1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <vector> | |
#define inline __attribute__((always_inline)) | |
namespace { | |
template <typename Iterator, typename Value, typename Checker> | |
class EasyIterator { | |
public: | |
inline Iterator& begin() { | |
this->operator++(); | |
return static_cast<Iterator&>(*this); | |
} | |
inline Iterator const& end() const { return static_cast<Iterator const&>(*this); } | |
inline bool operator!=(Iterator&) const { return !Checker()(value_); } | |
inline void operator++() { value_ = static_cast<Iterator&>(*this).Next(); } | |
inline Value operator*() const { return value_; } | |
private: | |
Value value_; | |
}; | |
struct IsNull { | |
inline bool operator()(int x) const { return x == 0; } | |
}; | |
class MyIterator : public EasyIterator<MyIterator, int, IsNull> { | |
public: | |
MyIterator(std::vector<int> const& objects) : objects_(objects) {} | |
int Next() { return objects_[index_++]; } | |
private: | |
int index_ = 0; | |
std::vector<int> const& objects_; | |
}; | |
} // namespace | |
void foo(std::vector<int> const& a) { | |
for (int i : MyIterator(a)) { | |
printf("%d\n", i); | |
} | |
} | |
void foo2(std::vector<int> const& a) { | |
MyIterator mi(a); | |
for (int i = mi.Next(); i >= 0; i = mi.Next()) { | |
printf("%d\n", i); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment