[英]std::begin and std::end iterators in Visual Studio
我正在尝试在Windows中编译nghttp2,opensource。 我已经在Linux中成功编译了相同的文件。
我面临以下代码的编译错误。 *
template <size_t N> struct Memchunk {
public:
Memchunk(Memchunk *next_chunk)
: pos(std::begin(buf)), last(pos), knext(next_chunk), next(nullptr) {}
size_t len() const { return last - pos; }
size_t left() const { return std::end(buf) - (const size_t) last; }
void reset() { pos = last = std::begin(buf); }
std::array<uint8_t, N> buf;
uint8_t *pos, *last;
Memchunk *knext;
Memchunk *next;
static const size_t size = N;
};
*
我收到以下错误。
error C2440: 'return': cannot convert from'std::_Array_const_iterator<_Ty,16384>' to 'std::size_t'
我没有在Linux中遇到上述错误。 我是否缺少特定于Visual Studio的内容?
问题可能源于std::begin()
在Linux上返回了一个指针,并在Windows中返回了一个正确的迭代器。 这加上一些错误。
如果将begin
和end
作为便利函数添加到类中,则如下所示:
template <size_t N> struct Memchunk {
uint8_t* begin() { return buf.data(); }
uint8_t* end() { return buf.data()+N; }
const uint8_t* begin() const { return buf.data(); }
const uint8_t* end() const { return buf.data()+N; }
// rest not shown
};
然后left()
可以实现为:
size_t left() const { return end() - last; }
可能会强制取消警告
现在可以在成员初始化列表中使用begin()
初始化pos
成员
这是Visual Studio插入额外的类型/调试信息。 有时这使其与标准算法不兼容。 就是说,这是您为运行/不足检测中一些非常出色的阵列所付出的代价,因此可以原谅。
幸运的是,解决方法很容易...
使用:std :: distance http://en.cppreference.com/w/cpp/iterator/distance
只要记住要反转参数ab == std :: distance(b,a)
让我知道这是否无效。
-----------修正案-------------
我只是尝试了您提供的示例,并意识到这不是真正的问题(尽管您会发现距离比迭代器算法更可移植)。 问题仍然是调试信息,但是您需要修复“ char * X = begin(buf)”
而是使用&array [0]
这为我编译
template <size_t N> struct Memchunk
{
public:
Memchunk(Memchunk *next_chunk)
: pos(&buf[0])
, last(pos)
, knext(next_chunk)
, next(nullptr)
{
}
size_t len() const { return distance(pos,last); }
size_t left() const { return std::distance(last,buf); }
void reset() { pos = last = std::begin(buf); }
std::array<uint8_t, N> buf;
uint8_t *pos, *last;
Memchunk *knext;
Memchunk *next;
static const size_t size = N;
};
(顺便说一句,您是否有充分的理由不使用std :: list?请在下面尝试这种方法)
template <size_t N> struct MemchunkImp
{
public:
MemchunkImp()
: pos(&buf[0])
, last(pos)
{
}
size_t len() const { return distance(pos,last); }
size_t left() const { return std::distance(last,buf); }
void reset() { pos = last = std::begin(buf); }
std::array<uint8_t, N> buf;
uint8_t *pos, *last;
static const size_t size = N;
};
template <size_t N> using Memchunk = std::list<MemchunkImp<N>>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.