首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用可增量型boost counting_iterator

使用可增量型boost counting_iterator
EN

Stack Overflow用户
提问于 2013-08-02 14:26:49
回答 1查看 1.1K关注 0票数 2

我试图在boost::counting_iterator中使用可增加的类型。

迭代器为可增量类型工作的boost::counting_iterator 文件上说,即为CopyConstructible、Assignable、PreIncrementable和EqualityComparable的类型。

我的累进型:

代码语言:javascript
复制
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;
};

这不能编译:

代码语言:javascript
复制
#include <boost/iterator/counting_iterator.hpp>
#include "incrementable.h"
int main() {
  boost::counting_iterator<Incrementable<int>> a(Incrementable<int>(0));
  return 0;
}

错误:

代码语言:javascript
复制
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,要么是为了:

  • 我的累进型counting_iterator,
  • 或者就像错误说的,对于我的可累加类型(这有意义吗?)我的可增量类型不是迭代器)。

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

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

代码语言:javascript
复制
namespace boost { namespace detail {
template <class T> struct is_numeric<Incrementable<T>>
    : mpl::true_ {};
}} // boost::detail namespace

现在,一切都如预期的那样编译和工作。尽管如此,我仍然怀疑图书馆是否会被这样使用。

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

Steve的建议:专门性std::numeric_limits也适用于:

代码语言:javascript
复制
namespace std {
template<class T>
class numeric_limits<Incrementable<T>> : public numeric_limits<T> {
public:
  static const bool is_specialized = true;
};
}

尽管如此,我还是不知道对于渐进式类型来说,这是否是正确的做法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-02 16:21:28

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

您链接到的文档中给出了Incrementable模板参数对counting_iterator的要求(从"iterator_category定义如下.“开始,因为实际需求部分引用了iterator_category)。

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18019393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档