简体   繁体   中英

What is T (& var)[N]?

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?

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.

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!

This is the way to declare a reference to an array of T (of size N) named left and right. The code is legal C++.

This allows you to pass in:

int ones[5] = { 1,1,1,1,1 };
int twos[5] = { 2,2,2,2,2 };

swap_impl(ones, twos);

Then template type inference will know that you have T = int and N = 5 and do the in-place swap. If you mismatch the types or the size, you get a handy compilation failure.

Yes this is standard C++ allowed from very early on (its basically C with the addition of a reference).

Using typedefs makes it easier to read:

int main()
{
    typedef  int (&MyArray)[4];
    int      data[4];
    MyArray  dataRef = data;
}

It sort of mirrors the function typedef

typedef int (*MyFunc)();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM