Created
November 24, 2018 17:59
-
-
Save nmmmnu/e52b9c34616fe47584dcf22685facba7 to your computer and use it in GitHub Desktop.
Iterator traits
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 <iterator> | |
#include <numeric> | |
class array{ | |
int d[5] = { 1, 2, 3, 4, 5 }; | |
public: | |
struct it{ | |
// traits section | |
using difference_type = unsigned; | |
using value_type = int; | |
using pointer = const value_type *; | |
using reference = value_type &; | |
using iterator_category = std::bidirectional_iterator_tag; | |
int p; | |
array const &a; | |
constexpr it(int const p, array const &a) : p(p), a(a){} | |
bool operator ==(it const other) const{ | |
return p == other.p; | |
} | |
constexpr bool operator !=(it const other) const{ | |
return p != other.p; | |
} | |
constexpr int operator *() const{ | |
return a.d[p]; | |
} | |
it &operator ++(){ | |
++p; | |
return *this; | |
} | |
it &operator --(){ | |
--p; | |
return *this; | |
} | |
}; | |
public: | |
constexpr it begin() const{ | |
return { 0, *this }; | |
} | |
constexpr it end() const{ | |
return { 5, *this }; | |
} | |
}; | |
int main0(){ | |
constexpr array a; | |
int sum = 0; | |
// works without traits | |
for(auto const &x : a) | |
sum += x; | |
return sum; | |
} | |
int main1(){ | |
constexpr array a; | |
// works without traits | |
return std::accumulate(std::begin(a), std::end(a), 0); | |
} | |
constexpr int main2(){ | |
constexpr array a; | |
// NOT works without traits | |
using len = std::iterator_traits<array::it>::difference_type; | |
len const count = std::distance(std::begin(a), std::end(a)); | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment