Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is T (& var)[N]?

Tags:

c++

boost

In boost/utility/swap.hpp I have found this piece of code:

template<class T, std::size_t N>
void swap_impl(T (& left)[N], T (& right)[N])
{
  for (std::size_t i = 0; i < N; ++i)
  {
    ::boost_swap_impl::swap_impl(left[i], right[i]);
  }
}

What are left and right? Are they references to arrays? Is this code allowed by C++ ISO standard 2003 or later?

like image 898
Mihran Hovsepyan Avatar asked Dec 21 '22 15:12

Mihran Hovsepyan


2 Answers

A reference to an array of type T and length N.

This is a natural extension of C's pointer-to-array syntax, and is supported by C++03.

You could use cdecl.org to try to parse these complex type declarations.

like image 128
kennytm Avatar answered Dec 24 '22 03:12

kennytm


What are left and right? Are they references to arrays? Is this code allowed by C++ ISO standard 2003 or later?

Yes. They're references to arrays.

That means, you can call swap_impl as:

int a[10]; //array
int b[10];
//...
swap_impl(a,b); //correct

But you cannot call swap_impl as:

int *a = new int[10]; //pointer 
int *b = new int[10];
//...
swap_impl(a,b); //compilation error

Also note that you cannot do even this:

int a[10];
int b[11];
//...
swap_impl(a,b); //compilation error - a and b are arrays of different size!

Important point:

- Not only arguments must be arrays, but the arrays must be of same size!

like image 34
Nawaz Avatar answered Dec 24 '22 04:12

Nawaz