Skip to content

Instantly share code, notes, and snippets.

@rioki
Created April 25, 2022 13:24
Show Gist options
  • Save rioki/b745e8f7c3a60bc18faa4594ffdb676b to your computer and use it in GitHub Desktop.
Save rioki/b745e8f7c3a60bc18faa4594ffdb676b to your computer and use it in GitHub Desktop.
Iterator wrapper that allows to use two iterators in range based for loop.
template <typename T>
struct iterator_wrapper
{
iterator_wrapper(T&& begin, T&& end) noexcept
: m_begin{std::forward<T>(begin)}, m_end{std::forward<T>(end)} {}
const T& begin() const noexcept
{
return m_begin;
}
const T& end() const noexcept
{
return m_end;
}
private:
T m_begin;
T m_end;
};
template <typename T>
iterator_wrapper<T> make_iterator_wrapper(T&& begin, T&& end) noexcept
{
return {std::forward<T>(begin), std::forward<T>(end)};
}
TEST(iterator_wrapper, for_each)
{
std::vector<int> values = {1,2,3,4,5,6,7,8,9};
auto r = 1;
for (auto& i : make_iterator_wrapper(std::begin(values), std::end(values)))
{
EXPECT_EQ(r, i);
r++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment