Reputation: 215
I have a class whose data container is backed by an array, and I have the following implementations for begin()
and 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);
}
In other member functions, I am attempting to use begin()
and end()
for STL algorithms such as std::transform
and std::copy
. When const
objects are passed as parameters to these member functions, I encounter the error:
error: passing '
const MyContainerClass<size>
' as 'this
' argument discards qualifiers.
note: in call to 'double* MyContainerClass<size>::begin()
[withunsigned int size = size
]'
Is this caused by incorrect begin()
and end()
implementations?
std::copy(begin(), end(), someOutputIterator);
Upvotes: 2
Views: 167
Reputation: 2474
The important word here is 'const': You need to provide additional const
versions of your begin()
and end()
functions, that return const double*
.
If you are using C++ 11, you may also want to provide cbegin()
and cend()
.
Upvotes: 4
Reputation: 227400
Is this caused by incorrect begin() and end() implementations?
Yes, you need const
versions of the functions. For example:
template <size_t size>
const double * MyContainerClass<size>::begin() const {
return std::begin(mContainer);
}
Upvotes: 4