6

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)));
4
  • 1
    Use an array_view. Commented Oct 24, 2015 at 20:05
  • 1
    @KarolyHorvath, OP knows that there are other ways of implementing this or using containers. Commented Oct 24, 2015 at 20:10
  • In С++ you can use templates: template <std::size_t N> void byref(int (&a)[N]); Commented Oct 24, 2015 at 20:31
  • @Constructor What if the function only wants to deal with 5 elements? Commented Oct 24, 2015 at 20:47

2 Answers 2

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));
}
Sign up to request clarification or add additional context in comments.

Comments

0

With this prototype, I fail to see another way to proceed than casting.

Typically, I see this one too: byref((int(&)[5])*(b + 5));, but of course it's the same and less safe than yours.

So, I don't see any clear and pretty way to do it (except for a macro maybe). I will upvote your question however, in order to see if you are missing something here!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.