I'd like to implement a simple native C++ fixed-capacity array template class, supporting the range-based "for each" syntax for convenience, with minimal overhead.
I'm having trouble with supporting it on const instances.
With this implementation:
template< class T, size_t Capacity >
class List
{
public:
List() { mSize = 0; }
const T* begin() const { return mItems; }
const T* end() const { return mItems + mSize; }
T* begin() { return mItems; }
T* end() { return mItems + mSize; }
private:
size_t mSize;
T mItems[ Capacity ];
};
and this usage:
const List< int, 5 > myInts;
for each( const int myInt in myInts )
{
continue;
}
I get this error:
error C2440: 'initializing' : cannot convert from 'const int *' to 'int *'
Conversion loses qualifiers
This usage doesn't complain:
List< int, 5 > myInts;
for each( const int myInt in myInts )
{
continue;
}
And this (undesirable) implementation doesn't complain:
template< class T, size_t Capacity >
class List
{
public:
List() { mSize = 0; }
T* begin() const { return const_cast< List* >( this )->mItems; }
T* end() const { return const_cast< List* >( this )->mItems + mSize; }
private:
size_t mSize;
T mItems[ Capacity ];
};
What is going on under the hood that I'm not understanding? What is it about std::vector<> that handles this properly? Thanks!