使用Incrementale类型的boost counting_迭代器

Using boost counting_iterator with Incrementable type

本文关键字:counting 迭代器 boost Incrementale 类型 使用      更新时间:2023-10-16

我正在尝试将Incrementale类型与boost::counting_iterator一起使用。

boost::counting_iterator文档指出,迭代器适用于可增量类型,即CopyConstructable、Assignable、PreIncrementale和EqualityComparable类型。

我的可增量类型:

template<class T> struct Incrementable {
  // CopyConstructible:
  Incrementable() : value(0) {}
  Incrementable(const Incrementable& other) : value(other.value) {}
  explicit Incrementable(const T& other) : value(other) {}
  // Assignable:
  inline Incrementable& operator=(const Incrementable& other) {
    value = other.value;
    return *this;
  }
  // PreIncrementable:
  inline Incrementable& operator++() {
    ++value;
    return *this;
  }
  // EqualityComparable:
  friend 
  inline bool operator==(const Incrementable& a, const Incrementable& b) {
    return a.value == b.value;
  }
  T value;
};

这无法编译:

#include <boost/iterator/counting_iterator.hpp>
#include "incrementable.h"
int main() {
  boost::counting_iterator<Incrementable<int>> a(Incrementable<int>(0));
  return 0;
}

错误:

usr/local/include/boost/iterator/iterator_categories.hpp:161:60: error: no type named 'iterator_category' in 'boost::detail::iterator_traits<Incrementable<int> >'
        typename boost::detail::iterator_traits<Iterator>::iterator_category

我想我需要为实现迭代器类别

  • 我的Incrementale类型的counting_迭代器
  • 或者,正如错误所说,对于我的Incrementale类型(这有意义吗?我的Incmmentale类型不是迭代器

从文档中(完全省略了这个主题),两者都不清楚,我在库的其他部分也找不到任何关于它的信息。

因此,我在boost::detail命名空间中添加了以下内容:

namespace boost { namespace detail {
template <class T> struct is_numeric<Incrementable<T>>
    : mpl::true_ {};
}} // boost::detail namespace

现在一切都按预期编译和工作。尽管如此,我真的很怀疑这个库是否打算以这种方式使用。

有人知道实现这一点的正确/干净的方法吗?

Steve Jessop的建议:专门化std::numeric_limits也有效:

namespace std {
template<class T>
class numeric_limits<Incrementable<T>> : public numeric_limits<T> {
public:
  static const bool is_specialized = true;
};
}

不过,我不知道这对一个会增加的类型来说是否是正确的做法。

我不确定Boost是否如您所说定义了"可增量类型"。如果它确实像你说的那样定义了它,那么就有一个文档错误,它不应该说counting_iterator适用于"任何可增加的类型",因为这些并不是全部需求。或者,如果"假设您正确地指定了其他模板参数"不用说,我想这是真的。

counting_iteratorIncrementable模板参数的要求在您链接到的文档中给出(从"iterator_category定义如下…"开始,因为实际要求部分指的是iterator_category)。

你不应该专门研究boost::detail::is_numeric。你应该专门研究std::numeric_limits。但在您的示例中,我认为您实际上已经过多地缩小了T的接口,以至于不能声称您的类型是数字类型(它没有算术)。如果您的类型既不是数字也不是迭代器,我认为您应该将CategoryOrTraversal指定为forward_iterator_tag。我可能错过了什么。