0

Is it possible to return a static fixed size array from a function? What would be the syntax for this. I am not asking for std::array, neither for T*, I am specifically asking for arrays of the form T arr[N]. For instance one can take such an array as an argument in a function through the following syntax:

template<typename T, auto N>
void func(T (&arr)[N])
{

}
3
  • Not entirely certain what you are asking, but If the array is scoped within the function, as in void func() { T arr[N]; }, it is dead at the end of the function. Commented Jul 6, 2019 at 0:56
  • @user4581301 I want to treat it like an object and return a copy (possibly with copy elision). Is this infeasible? Commented Jul 6, 2019 at 0:59
  • 2
    You return the array, it decays to a pointer and expires. Pretty much the only way to get one out is to wrap it in a a class, and if you're going to do that, ta-dah, poor-man's std::array. Commented Jul 6, 2019 at 1:03

1 Answer 1

2

A function cannot return an array by value. You have observed that a function can take an array as an argument by reference; similarly a function can return an array by reference. To do so, it would be easiest to use the trailing return type syntax:

auto func() -> T (&)[N];

But arrays can be neither passed nor returned by value.

Sign up to request clarification or add additional context in comments.

2 Comments

This answers my question more than adequately. What is the reason as to why T(&)[N] cannot be at the place of the return type directly and but auto is necessary (I tried it, it didn't work)?
@lightxbulb It can be done, but most people get the syntax wrong. coliru.stacked-crooked.com/a/ce8c356e17c9a2f4

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.