My understanding of typedef is to give a declaration an alias. Such the declaration for int will now be referred to as Integer. But why? Why would someone use typedef? What's the more advantageous reason?
typedef int Integer;
Integer blamo = 50;
cout << blamo << endl;
Code Clarity:In the case of the structure and union, it is very good to use a typedef, it helps to avoid the struct keyword at the time of variable declaration. You can also give a meaningful name to an existing type (predefined type or user-defined type).
One good reason to use typedef is if the type of something may change. For example, let's say that for now, 16-bit ints are fine for indexing some dataset because for the foreseeable future, you'll have less than 65535 items, and that space constraints are significant or you need good cache performance.
typedef is a predefined keyword. You can replace the name of the existing data type with the name which you have provided. This keyword helps in creating a user-defined name for an existing data type. You can also use the typedef keyword with structures, pointers, arrays etc.
Best PracticesUse a typedef for each new type created in the code made from a template. Give the typedef a meaningful, succinct name. Sometimes, typedefs should also be created for simple types. Again, a uniquely identifiable, meaningful name for a type increases maintainablity and readability.
that isn't a good example because Integer
and int
don't have any different meaning. But imagine something like,
typedef int BlamoType;
Now, in the future when 'blamo' becomes a 64-bit integer, you can just change this typedef, and all other code stays the same.
Another reason for typedef is to shorten type names. For example instead of
boost::shared_ptr<std::map<std::wstring, std::vector<int> > > blamo1;
boost::shared_ptr<std::map<std::wstring, std::vector<int> > > blamo2;
std::vector<boost::shared_ptr<std::map<std::wstring, std::vector<int> > > > blamoList;
you can do:
typedef boost::shared_ptr<std::map<std::wstring, std::vector<int> > > BlamoType;
BlamoType blamo1;
BlamoType blamo2;
std::vector<BlamoType> blamoList;
A reason that no-one mentioned here: to write generic code. Consider an implementation of some container like std::vector
. It should have a type called std::vector<T>::value_type
so anyone that writes generic code could use it:
template<class Container> void f(const Container &c)
{
typename Container::value_type v = c.back();
// ...
}
How can you introduce such a type into your class? The only way is a typedef:
// !!!EXPOSITION ONLY!!!
template<class T> class vector
{
public:
typedef T value_type;
// ...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With