Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function with a reference to an unknown size array?

Tags:

c++

arrays

syntax

Consider a valid code:

template<size_t size>
void by_numbered_reference(int (&array)[size]);

This function accepts an array as an argument and compiler can deduce the size of it using template argument deduction.

Now it is valid (tested on Apple clang version 3.0) to define such function:

void by_reference(int (&array)[], int size);

Which (should) accept a reference to an unknown size array as an argument. Noting that int[] and int[n] are distinct types and generally are incompatible.

The only way which I found how to invoke this function is:

int * array;
by_reference(reinterpret_cast<int(&)[]>(*array), array_size);
  1. Why does the language accept a reference to an unknown size array as a valid function argument, while there is no straightforward way to define such variable?
  2. Are there any known use cases where this syntax is required?
  3. Why void by_reference(int (*&array), int size) should not be used instead?
like image 495
Vytis Valentinavičius Avatar asked Sep 16 '13 13:09

Vytis Valentinavičius


1 Answers

Your assumption is wrong, the program is ill-formed. See C++11 standard 8.3.5/8:

If the type of a parameter includes a type of the form “pointer to array of unknown bound of T” or “reference to array of unknown bound of T,” the program is ill-formed.

clang allows this as a compiler extension. g++, for example, will not accept it.

You can however use templates to deduce the size of the passed array:

template <std::size_t N>
void by_reference(int (&)[N])
{
    // whatever
}
like image 94
nijansen Avatar answered Oct 02 '22 01:10

nijansen