【问题标题】:Using boost counting_iterator with Incrementable type将 boostcounting_iterator 与 Incrementable 类型一起使用
【发布时间】:2013-08-03 20:55:12
【问题描述】:

我正在尝试使用带有 boost::counting_iterator 的 Incrementable 类型。

迭代器适用于 Incrementable 类型的 boost::counting_iterator documentation says,即 CopyConstructible、Assignable、PreIncrementable 和 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

我猜我需要实现一个 iterator_category :

  • 我的 Incrementable 类型的counting_iterator,
  • 或者正如错误所说,对于我的 Incrementable 类型(这是否有意义?我的 Incrementable 类型 不是迭代器)。

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

所以我将以下内容添加到 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;
};
}

我仍然不知道这对于可递增类型是否正确。

【问题讨论】:

    标签: c++ boost iterator boost-iterators


    【解决方案1】:

    我不确定 Boost 是否像你说的那样定义了“可增量类型”。如果它确实如您所说定义,那么存在文档错误,它不应该说 counting_iterator 适用于“任何可递增类型”,因为这些不是全部要求。或者我想如果“只要你正确指定了其他模板参数”就不用说了。

    counting_iteratorIncrementable 模板参数的要求在您链接到的文档中给出(从“iterator_category 定义如下...”开始,因为实际要求部分参考回@987654325 @)。

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

    【讨论】:

      猜你喜欢
      • 2015-09-12
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 2011-02-13
      相关资源
      最近更新 更多