Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array by reference - subset of a larger array

Tags:

c++

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)));
like image 527
Neil Kirk Avatar asked Oct 24 '15 19:10

Neil Kirk


1 Answers

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));
}
like image 96
Andrey Nasonov Avatar answered Sep 30 '22 14:09

Andrey Nasonov