2017-04-03 3 views
2

데이터 컨테이너에 배열이있는 클래스가 있는데 begin()end()에 대한 다음 구현이 있습니다. 다른 멤버 함수에서 STL 알고리즘의 begin() 및 end()

template <size_t size> 
double * MyContainerClass<size>::begin(){ 
    return std::begin(mContainer); 
} 

template <size_t size> 
double * MyContainerClass<size>::end(){ 
    return std::end(mContainer); 
} 

, 나는 그런 std::transformstd::copy 같은 STL 알고리즘의 begin()end()를 사용하려고 시도하고있다.

error: passing ' const MyContainerClass<size> ' as ' this ' argument discards qualifiers.
note: in call to ' double* MyContainerClass<size>::begin() [with unsigned int size = size ]'

이가 잘못 begin()end() 구현에 의해 발생합니다 : const 객체가이 멤버 함수에 매개 변수로 전달하면, 나는 오류가 발생?

std::copy(begin(), end(), someOutputIterator); 

답변

4

Is this caused by incorrect begin() and end() implementations?

예, 당신은 기능의 const 버전이 필요합니다.

template <size_t size> 
const double * MyContainerClass<size>::begin() const { 
    return std::begin(mContainer); 
} 
+0

STL 알고리즘을 완벽하게 준수하려면 const 및 non-const 구현을 모두 제공해야합니까, 아니면 내 클래스의 응용 프로그램에 종속적입니까? – Skipher

+0

예, 일반적으로 둘 다 제공해야합니다. – CompuChip

+2

@Skipher 컨테이너의 데이터를 반복자를 통해 수정할 수있게하려면 비 const 버전 만 필요합니다. – juanchopanza

4

여기서 중요한 단어는 'CONST'입니다 : 예를 들어, 당신은 const double*를 반환하여 begin()end() 기능의 추가 const 버전을 제공해야합니다.

C++ 11을 사용하는 경우 cbegin()cend()을 제공 할 수도 있습니다.