xmllmx xmllmx - 3 months ago 8
C++ Question

Is it possible to use -1 to fetch the last element of a container/array?

What I want is illustrated as follows:

int array[4] { 1, 2, 3, 4 };
auto n1 = array[-1];
assert(4 == n1);
auto n2 = array[-2];
assert(3 == n2);

std::vector coll { 1, 2, 3, 4 };
auto n3 = coll[-1];
assert(4 == n3);
auto n4 = coll[-2];
assert(3 == n4);


I tried the following template function:

template<typename C, typename I>
constexpr decltype(auto) operator [](const C& coll, I idx)
{
if (idx >= 0)
{
return coll[idx];
}
else
{
return coll[std::size(coll) + idx];
}
}


But Clang complains:


error : overloaded 'operator[]' must be a non-static member function

constexpr decltype(auto) operator [](const C& coll, I idx)


Is it possible to correctly implement the function in modern C++?

Answer

You can't overload operator[] for a raw array.

But you can just define some named functions, e.g., off the cuff:

using Index = ptrdiff_t;

template< class Item, size_t n >
auto item( Index const i, Item (&a)[n] )
    -> Item&
{ return (i < 0? a[Index( n ) + i] : a[i]); }

Then the test code for raw arrays, suitably adapted, would be like

int array[] { 1, 2, 3, 4 };
int n1 = item( -1, array );
assert( 4 == n1 );
int n2 = item( -2, array );
assert( 3 == n2 );

I leave a definition for a general collection like std::vector, as an exercise for the reader. :)

Comments