Estoy un poco confundido acerca de si debo usar typedef en C ++ y cuándo. Creo que es un acto de equilibrio entre legibilidad y claridad.
Aquí hay un ejemplo de código sin ninguna definición de tipo:
int sum(std::vector<int>::const_iterator first,
std::vector<int>::const_iterator last)
{
static std::map<std::tuple<std::vector<int>::const_iterator,
std::vector<int>::const_iterator>,
int> lookup_table;
std::map<std::tuple<std::vector<int>::const_iterator,
std::vector<int>::const_iterator>, int>::iterator lookup_it =
lookup_table.find(lookup_key);
if (lookup_it != lookup_table.end())
return lookup_it->second;
...
}
IMO bastante feo. Así que agregaré algunos typedefs dentro de la función para que se vea mejor:
int sum(std::vector<int>::const_iterator first,
std::vector<int>::const_iterator last)
{
typedef std::tuple<std::vector<int>::const_iterator,
std::vector<int>::const_iterator> Lookup_key;
typedef std::map<Lookup_key, int> Lookup_table;
static Lookup_table lookup_table;
Lookup_table::iterator lookup_it = lookup_table.find(lookup_key);
if (lookup_it != lookup_table.end())
return lookup_it->second;
...
}
El código aún es un poco torpe, pero me deshago de la mayoría de los materiales de pesadilla. Pero todavía existen los itadores de vectores int, esta variante se deshace de ellos:
typedef std::vector<int>::const_iterator Input_iterator;
int sum(Input_iterator first, Input_iterator last)
{
typedef std::tuple<Input_iterator, Input_iterator> Lookup_key;
typedef std::map<Lookup_key, int> Lookup_table;
static Lookup_table lookup_table;
Lookup_table::iterator lookup_it = lookup_table.find(lookup_key);
if (lookup_it != lookup_table.end())
return lookup_it->second;
...
}
Esto se ve limpio, pero ¿sigue siendo legible?
¿Cuándo debo usar typedef? ¿Tan pronto como tenga un tipo de pesadilla? ¿Tan pronto como ocurre más de una vez? ¿Dónde debo ponerlos? ¿Debo usarlas en firmas de funciones o guardarlas en la implementación?