I know there are other ways of implementing this or using containers. This is just to satisfy my curiosity. Suppose I have the following code:
void byref(int (&a)[5]);
int main()
{
int a[5];
byref(a);
}
An advantage of passing a C-style array by reference is that sizeof
will work on it, as will std::end
. But now it is only possible to pass an array of exactly this size.
Is it possible to pass a subset of a larger array to this function by reference? For example, I'd like to do:
int main()
{
int a[10];
byref(a + 1);
}
Is there any way to make this work?
I got it to build and run, giving expected values in VS2015, but of course the code looks very dodgy:
byref(reinterpret_cast<int(&)[5]>(*(a + 1)));
I have only an idea of wrapping the bad looking cast into a function:
#include <iostream>
#include <cassert>
void byref(int (&a)[5])
{
std::cout << "Hello!" << std::endl;
}
template <size_t M, class T, size_t N>
T (&subarray(T (&a)[N], size_t start))[M]
{
assert(start < N && start + M <= N);
return reinterpret_cast<T(&)[M]>(a[start]);
}
int main()
{
int a[5], b[8];
byref(a);
byref(subarray<5>(subarray<6>(b, 0), 1));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With