Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange declaration with using in C++

Tags:

c++

c++11

On a piece of code in a previous question in stackoverflow I saw this, strange to me, declaration with using:

template <std::size_t SIZE> 
class A
{
public:
  ...
  using const_buffer_t = const char(&)[SIZE];
  ...
};

Could someone please address the following questions:

  1. What type it represents?
  2. Where do we need such kind of declarations?
like image 440
101010 Avatar asked Apr 25 '14 14:04

101010


2 Answers

That's a type alias, a new syntax available since c++11.

What you're actually doing is typedefing the type of an array

const_buffer_t 

will be an array of const char with length = SIZE

like image 71
Nikos Athanasiou Avatar answered Oct 22 '22 10:10

Nikos Athanasiou


That using declaration is a new syntax introduced in C++11; it introduces a type alias, specifying that const_buffer_t is now an alias for the type const char(&)[SIZE]. In this respect, this use of using is substantially identical to a typedef (although using type aliases are more flexible).

As for the actual type we are talking about (const char(&)[SIZE]), it's a reference to an array of size SIZE; references to array are rarely used, but can have their use:

  • if in some function you want to enforce receiving a reference to an array of a specific size instead of a generic pointer, you can do that with array references (notice that even if you write int param[5] in a function declaration it's parsed as int *);
  • the same holds for returing references to array (documenting explicitly that you are returning a reference to an array of a specific size);
  • more importantly, if you want to allocate dynamically "true" multidimensional arrays (as opposed to either an array of pointers to monodimensional array or a "flat array" with "manual 2d addressing") you have to use them.

See also the array FAQ, where much of this stuff is explained in detail.

like image 29
Matteo Italia Avatar answered Oct 22 '22 11:10

Matteo Italia