我试图在boost::counting_iterator中使用可增加的类型。
迭代器为可增量类型工作的boost::counting_iterator 文件上说,即为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,要么是为了:
从文档中两者都不清楚(完全省略了这个主题),而且我在库的其他部分也找不到关于这个主题的任何信息。
因此,我向boost::detail命名空间添加了以下内容:
namespace boost { namespace detail {
template <class T> struct is_numeric<Incrementable<T>>
: mpl::true_ {};
}} // boost::detail namespace现在,一切都如预期的那样编译和工作。尽管如此,我仍然怀疑图书馆是否会被这样使用。
有人知道正确/干净的方式来实现这一点吗?
Steve的建议:专门性std::numeric_limits也适用于:
namespace std {
template<class T>
class numeric_limits<Incrementable<T>> : public numeric_limits<T> {
public:
static const bool is_specialized = true;
};
}尽管如此,我还是不知道对于渐进式类型来说,这是否是正确的做法。
发布于 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。我可能漏掉了什么。
https://stackoverflow.com/questions/18019393
复制相似问题