The power of 'typedef' in C++

C++ allows the definition of our own types based on other existing data types. We can do this using the keyword typedef, whose format is:

typedef existing_type new_type_name ;

where existing_type is a C++ fundamental or compound type and new_type_name is the name for the new type we are defining.

For example:
typedef char C;
typedef unsigned int WORD;
typedef char * pChar;
typedef char field [50];

There are many scenarios where using typedef's are very advantageous. The following program is written based on the reasons for using typedef's as defined by Herb Sutter in his book "More Exceptional C++"



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program showing the advantages of using typedefs in C++

#include<iostream>
#include<map>
#include<vector>
#include<list>
#include<assert.h>

using namespace
std;

//Comment/Uncomment as required
//#define USING_MAPS
#define USING_OTHER_STL

//5 - Portability: Useful if different users want to use different STL classes
#if defined USING_MAPS
typedef map<int,int> table; //1 - Typeability: table is easier to type
#else
//4 - Flexibility: In future you could replace a map by a vector for example
typedef vector<int> table;
//typedef list<int> table;
#endif

typedef
table::iterator tableIter;

//map<int,int> multiplicationTableTill10(int num); - not very readable
table multiplicationTableTill10(int num); //2 - Readability: Easier to read

int
main()
{

int
i = 1;
table t = multiplicationTableTill10(7);
for
(tableIter t_iter = t.begin(); t_iter != t.end(); ++t_iter, ++i)
{

#if defined USING_MAPS
cout<<"7 * "<<i<<" = "<<t[i]<<endl;
#elif defined USING_OTHER_STL
cout<<"7 * "<<i<<" = "<<*t_iter<<endl;
#else
assert(0);
#endif
}
return
0;
}


typedef
int Multiplier; //int is also now written as Multiplier

//This program creates a multiplication table of the number input from 1 to 10
table multiplicationTableTill10(int num)
{

table t;
tableIter t_iter;
//3 - Communication: Multiplier is more meaningful then int in the case below
for(Multiplier i = 1; i <= 10; i++)
{

#if defined USING_MAPS
t[i] = num * i;
#elif defined USING_OTHER_STL
t_iter = t.end();
t.insert(t_iter, num * i);
#else
assert(0);
#endif
}
return
t;
}






The Output is as follows:



More information on Typedefs:


Check out this stream