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++?
operator[]
, which must be member function. – songyuanyaoif (idx >= 0)
. Otherwisex[0]
will give you one element beyond the end of the array, which won't end well :-) – paxdiablostd::size(coll) + idx
will cause wrap-around in the range ofsize_t
, due to the impractical return type of C++17std::size
. – Cheers and hth. - Alf