Using c++ typedef/using type alias

后端 未结 3 854
不知归路
不知归路 2021-01-03 21:59

I am reading C++ primer book and completely don\'t understand one line:

 using int_array = int[4]; 
 typedef int int_array[4]; // This line
 for (int_array *         


        
3条回答
  •  [愿得一人]
    2021-01-03 22:09

    TL;DR

    Both are doing the exact same thing: Defining int_array as an alias of an array of 4 ints

    Making Sense of the Syntax

    using has a nice A = B notation that is generally much easier to understand.

    using alias = type;
    

    typedef's notation is not quite backward. For a simple typedef

    typedef type alias;
    

    but more complicated typedefs tend to sprawl. I suspect the syntax was modeled after how one would define a variable, but I can't find where I packed my copy of the old K&R C programming book and can't look that up at the moment.

    int int_array[4];
    

    would define int_array to be an array of 4 ints. Slapping typedef on the front

    typedef int int_array[4];
    

    makes int_array a type alias instead of a variable.

    Another example,

    int * intp;
    

    Defines intp to be a pointer to an int.

    typedef int * intp;
    

    Defines intp to be an alias to the type pointer to an int.

    This gets ugly with more complicated data types as the name of the typedefed alias may be buried somewhere in the middle of the definition. A typedefed function pointer for example:

    typedef void (*funcp)(param_t param1, param_t param2, ...);
    

    vs using

    using funcp = void (*)(param_t param1, param_t param2, ...);
    

    Making a 2D Array

    If you want a 2D array you could

    using int_array2D = int[4][4];
    

    or you could define an array of int_array

    using int_array2D = int_array[4];
    

    And of course that means you can

    using int_array3D = int_array2D[4];
    

    and keep on going until the cows come home or you've packed on so many dimensions that The Doctor's brain melts.

提交回复
热议问题