使用Incrementale类型的boost counting_迭代器
Using boost counting_iterator with Incrementable type
我正在尝试将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_iterator
的Incrementable
模板参数的要求在您链接到的文档中给出(从"iterator_category
定义如下…"开始,因为实际要求部分指的是iterator_category
)。
你不应该专门研究boost::detail::is_numeric
。你应该专门研究std::numeric_limits
。但在您的示例中,我认为您实际上已经过多地缩小了T
的接口,以至于不能声称您的类型是数字类型(它没有算术)。如果您的类型既不是数字也不是迭代器,我认为您应该将CategoryOrTraversal
指定为forward_iterator_tag
。我可能错过了什么。
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?