Wierd interface method for point Iterator

谁说我不能喝 提交于 2019-12-02 11:35:34
Yakk - Adam Nevraumont

I am going to argue for a different solution. Throw inheritance out.

Start with boost::any or std::any. Then add in type erasure.

Here are 3 operations you need for an iterator:

const auto increment = make_any_method<void()>( [](auto&&self){++self;} );
const auto equals = make_any_method<bool(boost::any const&), true>( [](auto const&lhs, boost::any const& rhs){
  using LHS=std::decay_t<decltype(lhs)> const;
  auto prhs = boost::any_cast<LHS>(&rhs);
  if (!prhs) return false;
  return lhs == *prhs;
} );
template<class T>
const auto deref = make_any_method<T()>( [](auto&&self)->T {return *self;} );

Now turn those operations into a proper iterator with a little fascade:

template<class T,
  class Base=super_any<decltype(increment), decltype(equals), decltype(deref<T>)>
>
struct poly_iterator:Base

{
  using Base::Base;
  using iterator_category = std::input_iterator_tag;
  using value_type = T;
  using difference_type = std::ptrdiff_t;
  using pointer = T*;
  using reference = T;

  friend bool operator==( poly_iterator const& lhs, poly_iterator const& rhs ) {
    return (lhs->*equals)(rhs);
  }
  friend bool operator!=( poly_iterator const& lhs, poly_iterator const& rhs ) {
    return !(lhs==rhs);
  }
  T operator*() {
    return ((*this)->*deref<T>)();
  }
  poly_iterator& operator++() {
    ((*this)->*increment)();
    return *this;
  }
  poly_iterator operator++(int) {
    std::cout << "i++\n";
    auto copy = *this;
    ((*this)->*increment)();
    return copy;
  }
};

Live example.

boost provides a similar system of type-erased iterators to a type T.

In general, this technique has performance implications, as following all those function pointers on every increment compare and dereference adds up.

Iterating over the permiter isn't a type of iteration, it is a range of iteration.

Same for iterating over a side (line) of the figure.

There are 3 ways to iterate over the perimeter. First, iterate over the lines in the perimeter, which then iterates over the points.

Second, iterating over the points of the perimeter.

Third, iterate over a pair of (side_type, point) or (side, point) where side has a property side_type.

This results in iteration that is compatible with range-for loops and C++ algorithms, removes the requirement to use smart pointers, and lets you treat your iterators as value-types. It moves the type system out of the way: the only thing that you have a type for is the thing you are iterating over, not the details of how you are walking.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!