2016-08-30 7 views
9

boost::circular_bufferを含むクラスを次に示します。structです。私はイテレータのtypedefを同梱のcircular_bufferに入れます。std :: upper_bound constメンバー関数のconstイテレータを返します

私の問題はこれです:doWork機能がconstマークされている場合、std::upper_boundの戻り値が返り値はboost::cb_details::const_traitsを有することに起因するMyIteratorタイプと互換性がありません。関数からキーワード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; }); 

は、自己完結型の例である:だから

#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; 
} 

、なぜこの関数はconstのすることはできませんか?なぜそれをマーキングするのがこの副作用を持っていますか?コンテナに非constイテレータが必要ですが、実際のテストケースではコンテナを実際に変更するつもりはありません。

+4

'doWork'が' const'なので、 'cb'も' const'として扱われます。 'doWork'は' cb'を変更するつもりはないので代わりに 'const_iterator'を使います。 –

+2

MCVE!不思議は決して止まらない。 +1 –

+1

@CaptainObvlious:回答セクションが下にあり、友人 –

答えて

7

constコンテナを効果的に観察しているので、const_iteratorが必要になります。

おそらく:

typedef typename boost::circular_buffer<Sample>::const_iterator MyConstIterator; 

&hellip; iterのいずれかにしてください。

誰かがあなたにautoでこれを回避できたと伝えます。それは本当ですが、あなたはこの「バグ」を発見したことはないでしょう。それともconst_iteratorが存在します。

+0

確かに私はconst_iterators、ありがとう! – Chris

4

機能がconstと表示されている場合、メンバー変数へのアクセスはすべてconstになります。

constコンテナは、イテレータが動作する方法であるconst_イテレータへのアクセスのみを許可します。

関連する問題