views:

90

answers:

4

In definition of pair class in c++ there are two typedefs. what are they for? there are no use of them in the code!

template <class T1, class T2> struct pair
{
  typedef T1 first_type;
  typedef T2 second_type;

  T1 first;
  T2 second;
  pair() : first(T1()), second(T2()) {}
  pair(const T1& x, const T2& y) : first(x), second(y) {}
  template <class U, class V>
    pair (const pair<U,V> &p) : first(p.first), second(p.second) { }
}
+5  A: 

It's to allow other pieces of code to declare variables of the types without having direct access to the type parameters (T1 & T2). A similar, less trivial, example are the typedefs in container classes:

vector<int>::iterator curNum;
for(curNum = someVect.begin(); curNum != someVect.end(); curNum++)
    ; //do stuff

This uses the typedef iterator defined in the vector template to create curNum. It will be somewhat less useful come C++0x's auto keyword:

for(auto curNum = someVect.begin(); curNum != someVect.end(); curNum++)
    ;
Cogwheel - Matthew Orlando
+1  A: 

They are public aliases of the passed-in T1 and T2 types that can be referenced after the object is constructed.

Joe
+3  A: 

This is so you can refer to the types in your code using e.g. pair<int,string>::first_type myVariable, or if you've typedef'd a particular flavour of the template then MyPair::first_type myVariable.

Will A
+6  A: 

They are just here for you convenience, so you can use them in your code. C++ doesn't have a reflection model , so that's the only way you have "know" what types they are Suppose you define your own pair

typedef pair MyPair;

Then you can use

MyPair::first_type
MyPair::second_type

for example,

MyPair::first_type my_first(MyPair& pair)
{
    return pair.first;
}

Then you won't need to research and replace everywhere in your code , if you change the original definition of MyPair.

mb14