std :: upper_bound返回const成员函数中的const迭代器

Chr*_*ris 9 c++ boost circular-buffer c++11

这是一个包含boost::circular_buffer一些的类struct.我为迭代器创建了一个typedef到包含的中circular_buffer.

我的问题是:当doWork标记函数时const,由于返回值的原因,返回的值std::upper_boundMyIterator类型不兼容boost::cb_details::const_traits.如果我const从函数中删除关键字,我的所有编译错误都会消失.

要清楚编译器错误是这样的:

error: conversion from ‘boost::cb_details::iterator<boost::circular_buffer<Wrapper<int>::Sample, std::allocator<Wrapper<int>::Sample> >, boost::cb_details::const_traits<std::allocator<Wrapper<int>::Sample> > >’ to non-scalar type ‘Wrapper<int>::MyIterator {aka boost::cb_details::iterator<boost::circular_buffer<Wrapper<int>::Sample, std::allocator<Wrapper<int>::Sample> >, boost::cb_details::nonconst_traits<std::allocator<Wrapper<int>::Sample> > >}’ requested    
                          [](const Sample& a, const Sample& b) { return a.foo < b.foo; });
Run Code Online (Sandbox Code Playgroud)

这是一个独立的例子:

#include <algorithm>
#include <boost/circular_buffer.hpp>

template <typename T>
class Wrapper {
 public:
    struct Sample {
        T foo;
    };

    typedef typename boost::circular_buffer<Sample>::iterator MyIterator;

    Wrapper(int size) { cb.resize(size); }

    void add(T val) { cb.push_back(Sample{val}); }

    void doWork(T bound) const {
        MyIterator iter =
            std::upper_bound(cb.begin(), cb.end(), Sample{3},
                         [](const Sample& a, const Sample& b) { return a.foo < b.foo; });
    }

    boost::circular_buffer<Sample> cb;
};

int main() {
    Wrapper<int> buf(100);
    buf.add(1);
    buf.add(5);
    buf.doWork(3);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

那么,为什么这个函数不能是const?为什么标记为const会产生这种副作用?我想在容器中使用非const迭代器,但在我的实际测试用例中,我并不打算实际修改容器.

Lig*_*ica 8

你需要一个const_iterator,因为你有效地观察了一个const容器.

也许:

typedef typename boost::circular_buffer<Sample>::const_iterator MyConstIterator;
Run Code Online (Sandbox Code Playgroud)

......然后制作iter其中一个.

有人会告诉你,你可以避免这种情况auto.这是真的,但是你永远不会发现这个"错误",或者const_iterator存在.