¿Qué significa esta declaración typedef?


En una página de referencia de C++ proporcionan algunos ejemplos de typedef y estoy tratando de entender lo que significan.

// simple typedef
typedef unsigned long mylong;


// more complicated typedef
typedef int int_t, *intp_t, (&fp)(int, mylong), arr_t[10];

Así que el simple typedef (la primera declaración) entiendo.

Pero, ¿qué están declarando con el segundo (repetido más abajo)?

typedef int int_t, *intp_t, (&fp)(int, ulong), arr_t[10];

En particular, ¿qué significa (&fp)(int, mylong)?

 76
Author: Jonathon Reinhart, 2014-02-27

5 answers

Está declarando varios typedefs a la vez, así como puede declarar varias variables a la vez. Son todos tipos basados en int, pero algunos se modifican en tipos compuestos.

Vamos a dividirlo en declaraciones separadas:

typedef int int_t;              // simple int
typedef int *intp_t;            // pointer to int
typedef int (&fp)(int, ulong);  // reference to function returning int
typedef int arr_t[10];          // array of 10 ints
 97
Author: Mike Seymour,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-27 07:30:43
typedef int int_t, *intp_t, (&fp)(int, mylong), arr_t[10];

Es equivalente a:

typedef int int_t;
typedef int *intp_t;
typedef int (&fp)(int, mylong);
typedef int arr_t[10];

En realidad hay un ejemplo similar en el estándar C++11:

C++11 7.1.3 El especificador typedef

A typedef-name no introduce un nuevo tipo como lo hace una declaración class (9.1) o una declaración enum.Ejemplo: después de

typedef int MILES , * KLICKSP ;

Las construcciones

MILES distance ;
extern KLICKSP metricp ;

Son todas declaraciones correctas; el tipo de distancia es int que de metricp es "puntero a int." -final ejemplo

 41
Author: Yu Hao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-27 07:35:56

Si tiene el comando cdecl, puede usarlo para desmitificar estas declaraciones.

cdecl> explain int (&fp)(int, char)
declare fp as reference to function (int, char) returning int
cdecl> explain int (*fp)(int, char)
declare fp as pointer to function (int, char) returning int

Si no tiene cdecl, debería poder instalarlo de la manera habitual (por ejemplo, en sistemas de tipo Debian, usando sudo apt-get install cdecl).

 32
Author: Amarghosh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-15 10:19:27

La parte (&fp)(int, mylong) representa una referencia a una función. No se recomienda que los programadores usen funciones en typedef por la misma razón por la que estás haciendo esta pregunta. Confunde a otras personas que miran el código.

Supongo que usan el typedef en algo como esto:

typedef unsigned long mylong; //for completeness
typedef int (&fp)(int, mylong);
int example(int param1, mylong param2);

int main() {
     fp fp_function = example;
     int x = fp_function(0, 1);
     return 0;
}

int example(int param1, mylong param2) {
     // does stuff here and returns reference
     int x = param1;
     return x;
}

Editado de acuerdo con el comentario de Brian:

int(&name)(...) es una referencia de función llamada name (la función devuelve un int)

int &name(...) es una función llamada name devolviendo una referencia a un int

Una referencia a una función que devuelve una referencia int se vería algo así: typedef int &(&fp)(int, mylong) (esto se compila en un programa, pero el comportamiento no está probado).

 0
Author: ub3rst4r,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-15 10:21:16

Typedef es definir un nuevo tipo para su uso en su código, como una taquigrafía.

typedef typename _MyBase::value_type value_type;
value_type v;
//use v

Typename aquí le permite al compilador saber que value_type es un tipo y no un objeto dentro de _MyBase.

El :: es el ámbito del tipo. Es algo así como "está en", por lo que value_type "está en" _MyBase. o también puede ser pensado como contiene.

Posible duplicado: C++ - significado de una sentencia que combina typedef y typename

 -7
Author: Harsh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:32:56