Strange declaration with using in C++

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:

  • What type it represents?
  • Where do we need such kind of declarations?

  • 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


    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.

    链接地址: http://www.djcxy.com/p/78648.html

    上一篇: 在C ++中使用完全限定的名称

    下一篇: 在C ++中使用奇怪的声明