boost::circular_buffer
일부를 포함하는 클래스입니다. struct
입니다. 반복자에 대한 typedef를 포함 된 circular_buffer
에 넣습니다.std :: upper_bound const 멤버 함수에서 const iterator를 반환합니다.
내 문제는 이것이다 다음 doWork
기능이 const
표시 될 때, std::upper_bound
의 반환 값이 반환 값이 boost::cb_details::const_traits
을 필요로 인해 MyIterator
유형과 호환되지 않습니다. 함수에서 const
키워드를 제거하면 모든 컴파일 오류가 사라집니다.
#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를 할 수 없습니다
다음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; });
은 자체에 포함 된 예입니다? const로 표시하는 것이 왜 부작용이 있습니까? 컨테이너에 비 const 반복자를 넣고 싶지만 실제 테스트 케이스에서는 컨테이너를 실제로 수정하려고하지는 않습니다.
'doWork'가'const'이기 때문에'cb'도'const'로 취급됩니다. 'doWork'는'cb'을 수정하려고하지 않으므로'const_iterator'를 대신 사용하십시오. –
MCVE! 불가사의는 결코 멈추지 않는다. +1 –
@CaptainObvlious : 답변 섹션이 친구 아래쪽에 있습니다. –